Tuesday, December 13, 2011

Writing Registry Key Default Values

 

PowerTip of the Day, from PowerShell.com:

 

If you need to set the default value for a Registry Key, you can  use either of these approaches:

Set-ItemProperty -Path HKCU:\Software\Somekey -Name ‘(Default)’ -Value MyValue

Or, you can just do this:

Set-Item -Path HKCU:\Software\Somekey -Value MyValue

 

thanks

Asking for Credentials

 

PowerTip of the Day, from PowerShell.com:

When you write functions that accept credentials as parameters, add a transformation attribute! This way, the user can either submit a credential object (for example, a credential supplied from Get-Credential), or simply a user name as string. The transformation attribute will then convert this string automagically into a credential and ask for a password.

function do-something {

param(

[System.Management.Automation.Credential()]

$Credential

)

'$Credential now holds a valid credential object'

$Credential

}

When you run do-something without parameters, it will automatically invoke the credentials dialog.

How to List Registry Hives

 

PowerTip of the Day, from PowerShell.com:

Use the provider name instead of a drive name when you need to get a list of all Registry Hives:

Dir Registry::

thanks

aman

My PowerShell Story: PowerShell and I

 

hi,

Thanks to http://www.powershellmagazine.com they just upload my powershell story yesterday.

13-12-2011 18-47-14

you can read the complete story here:  http://www.powershellmagazine.com/2011/12/12/powershell-and-i/

thanks

aman

Friday, December 2, 2011

Print All PDF Files in Folders using PowerShell

 

PowerTip of the Day, from PowerShell.com:

Try this one-liner if you need to print out all PDF documents you have stored in one folder:

Dir c:\myfolder\*.pdf | Foreach-Object { Start-Process -FilePath $_.FullName – Verb Print }

 


Thanks to www.powershell.com

Determining Service Start Modes using PowerShell

 

PowerTip of the Day, from PowerShell.com:

 

By using WMI, you can enumerate the start mode that you want your services to use. To get a list of all services, try this:

Get-WMIObject Win32_Service | Select-Object Name, StartMode

If you want to find out the start mode of one specific service, try this instead:

([wmi]'Win32_Service.Name="Spooler"').StartMode

Thanks to www.powershell.com
 

Change Service Start Mode using PowerShell

 

PowerTip of the Day, from PowerShell.com:

 

You can use WMI like this if you want to change a service start mode:

([wmi]'Win32_Service.Name="Spooler"').ChangeStartMode('Automatic').ReturnValue
([wmi]'Win32_Service.Name="Spooler"').ChangeStartMode('Manual').ReturnValue
 
Note that a return value of 0 indicates success. 
You will need Administrator privileges to change the start mode.
Thanks to www.powershell.com

“Enable or Disable” Network adapters using Powershell.

 

Hi,

In our IT environment we don’t give  “admin” rights to the normal users and they can’t enable/disable, install/un-install anything.

Today one of our users was having some problem with Wi-FI and to troubleshoot it i need to “enable” and “disable” Wi-Fi network adapter few times, but to enable or disable the network adapter i required to insert the “Administrator” username and password every time {remember my user don’t have admin privileges}.

network_1

This make me mad, i Inserted the username and password approx 10 times {somehow the problem was not resolved and with every change i need to disable and re-enable the wi-fi}, and I also don't want to login as administrator  to the system. Then i thought there must be a PowerShell way to do this and after few minutes of R&D i found the solution of my problem.

Problem:

user don’t have admin privileges to enable/disable any network adapters, so while troubleshooting if you need to enable or disable the network adapter it always ask for Administrator account to do the task.

 

network_1  network_2

Solution :

Run PowerShell as Administrator First

Search for PowerShell and then Right click and choose “Run as administrator

network_3

When PowerShell runs as Administrator, the PS path changed to “C:\widows\System32” and in title bar you can see the “Administrator” is written.

network_4

We will be using  WMI to enable and disable the network adapters.

I do remember that the WMI class for network adapter is start with win32_Network but i forget the full name of the class. lets search it first

  1: Get-WmiObject -List | where  { $_.Name -like "win32_network*"}

in above command we are listing all class in WMI and choosing those to display which starts with Win32_Network


It shows the all classes those are start with Win32_Network , the class which we need is Win32_NetworkAdapter


network_5


ok, lets query the Win32_NetworkAdapter class

  1: Get-WmiObject -Class win32_NetworkAdapter

and you see it shows the list of all network adapter installed in the system.


network_6 


lets filter it more and choose only Name of Adapter to display

  1: Get-WmiObject -Class win32_NetworkAdapter | select name

we piped the command further to Select-Object cmdlet and choose only to display name of the Network adpaters


network_7


Currently I am interested in enable/disable my Wi-Fi network Card. the Name of the  my Wi-Fi network adapter is “Intel(R) Centrino(R) Ultimate-N 6300 AGN


Now I will select only my “Intel(R) Centrino(R) Ultimate-N 6300 AGN” network adapter using where-object cmdlet and in $_.Name i am searching for that Name is Like something “ultimate-n”

  1: get-WmiObject win32_networkadapter |where { $_.name -like "*ultimate-n*"}

Now it showing only one Network Adapter and its showing the network adapter which i want to disable/enable. Our command is working fine till now.


network_8


Now I am going to put the above command in to a variable $wifi.

  1: $wifi = get-WmiObject win32_networkadapter |where { $_.name -like "*ultimate-n*"}

and lets also test the variable too.


All working fine ….


network_9


now pipe the $wifi to get-member cmdlet and check what the methods do we have

  1: $wifi | Get-Member -MemberType Method

NetworkAdapter has 4 methods but we are interested in only 2 for now, the enable and disable method.


To disable a Network adapter we need to use disable()


To enable a Network adapter we need to use enable()


network_10


lets try :)


first Disable it

$wifi.disable()

working


network_11


not enable it

  1: $wifi.enable()

it enabled :)


network_12


Now we can enable/disable network adapters number of times without inserting “Administrator” username and password again and again.


I hope it save someone's time :)


Thanks


Aman Dhally

Tuesday, November 29, 2011

“Smart Backup” using PowerShell


Hi,
As a Network Admin I always worry about my backups. I was planning to write a simple script which create a new folder by date and copy the desired files and folder in to it recursively.
so i successfully  able to write a script for it and sharing it with you and I hope it is useful to you too. {or at least for tally administrators they always worried about there data, or we can say they this article contain “How to Automate Tally Backup”
I am running this script on my Tally server:
Script Logic:
  1. Map a Network Drive where you want to save the backup
  2. Create a Folder by using Date as Name
  3. Copy the backup
  4. Create a log file name as “backup_log.txt”
  5. When all some send a email to admin ($to) with backup_log.txt as attachment.
  6. Remove the Map Drive
you can download the script from here : http://dl.dropbox.com/u/17858935/Smart_Backup_Create%20folders_by_Date.zip

Note : change \\T_server\Tally with your folder where you want to take backup.
          Change $source with your source folder which you want to backedup

Script:
1: #System Variable for backup Procedure
2:  $date = Get-Date -Format d.MMMM.yyyy
3:  New-PSDrive -Name "Backup" -PSProvider Filesystem -Root "\\T_Server\Tally"
4:  $source = "D:\Tally\Data\"
5:  $destination = "backup:\$date"
6:  $path = test-Path $destination
7: #Email Variables
8:  $smtp = "Exchange-server"
9:  $from = "Tally Backup <tally.backup@xyz.com>"
10:  $to = "Aman Dhally <amandhally@gmail.com>"
11:  $body = "Log File of TALLY bacupk is attached, backup happens on of Date: $date"
12:  $subject = "Backup on $date" 
13: # Backup Process started
14:  if ($path -eq $true) {
15:     write-Host "Directory Already exists"
16:     Remove-PSDrive "Backup"  
17:     } elseif ($path -eq $false) {
18:             cd backup:\
19:             mkdir $date
20:             copy-Item  -Recurse $source -Destination $destination
21:             $backup_log = Dir -Recurse $destination | out-File "$destination\backup_log.txt"
22:             $attachment = "$destination\backup_log.txt"
23: #Send an Email to User 
24:             send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Attachments $attachment -Body $body -BodyAsHtml
25:             write-host "Backup Sucessfull"
26:             cd c:\ 
27:  Remove-PSDrive "Backup"  
28:  }
I hope it may be useful to someone :) 
Thanks 
Aman Dhally

Storing Pictures in Active Directory

 

PowerTip of the Day, from PowerShell.com:

When you need to store a picture into an AD account, the picture will have  to be converted to byte values before it can be stored. Just make sure you adjust the path to the picture you want to store and the LDAP path of the AD object you want the picture to be stored in:

 

  1: # adjust picture path:
  2: $file = "C:\pic.jpg"
  3: $bild = New-Object system.Drawing.Bitmap($file)
  4:  
  5: $ms = New-Object IO.MemoryStream
  6: $bild.Save($MS, 'jpeg')
  7: $MS.Flush()
  8: $byte = $MS.ToArray()
  9: # adjust user LDAP path:
 10: $user = New-Object System.DirectoryServices.DirectoryEntry`
 11: 
 12: ("LDAP://10.17.141.219/CN=Tobias,CN=Users,DC=powershell,DC=local")
 13: 
 14: $User.Properties["jpegPhoto"].Value = $byte
 

$user.SetInfo()


 


Thanks to www.PowerShell.com

Monday, November 28, 2011

Finding IP and MAC address

 

PowerTip of the Day, from PowerShell.com:

 

Finding IP and MAC address

When you query network adapters with WMI, it is not easy to find the active network card. To find the network card(s) that are currently connected to the network, you can filter based on NetConnectionStatus which needs to be "2" for connected cards. Then you can take the MAC information from the Win32_NetworkAdapter class and the IP address from the Win32_NetworkAdapterConfiguration class and combine both into one custom return object:

PS> Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionStatus=2'

ServiceName : NETw5s64

MACAddress : 00:22:FA:D9:E1:50

AdapterType : Ethernet 802.3

DeviceID : 11

Name : Intel(R) WiFi Link 5100 AGN

NetworkAddresses :

Speed : 54000000

This gets you the network hardware but not the network configuration. To get the configuration data for this network card (like its IP address), get the related Win32_NetworkAdapterConfiguration instance:

########### Script Start Here ###########################

function Get-NetworkConfig {

Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionStatus=2' |

ForEach-Object {

$result = 1 | Select-Object Name, IP, MAC

$result.Name = $_.Name

$result.MAC = $_.MacAddress

$config = $_.GetRelated('Win32_NetworkAdapterConfiguration')

$result.IP = $config | Select-Object -expand IPAddress

$result

}

}

###################### Script end Here #####################

 

PS> Get-NetworkConfig

Name IP Mac

---- -- ---

Intel(R) WiFi Link 5100... {78.64.118.150, fe80::a... 00:22:FA:D9:E1:50

 

Thanks to www.PowerShell.com

“Script to list all folder of Outlook and total number of emails store in them” using PowerShell

 

Hi,

from past few days I tried to writing a script which shows me that how many folders I do have in my Outlook and total number of emails stored on them.

I get only 50% success so far, I am able to see the folders but somehow not able to see the total number of items store in them

Then I tried searching the Internet and found a script which does it. This script is written by well knows PowerShell MVP “Shay levy”

This script solve my problem and then i thought i should share it with you.

you can download the script from here:  http://dl.dropbox.com/u/17858935/ListOutlook_Folders_Total_Emails.zip

Screenshot of the output when you run script.

Before: When first time I run the Script

After: I removed 2 email from my “Junk-Junk” folder and test it again and precise result

Thanks “Shay”

screenshot

 

Thanks

Aman Dhally

Friday, November 25, 2011

“Find how many types of files you have in you laptop” using Powershell.

 

Hi

Today i was searching for one PDF file on my laptop and then I just thinks “How Many PDF files do i have?”, i have no idea, one way to find is go to windows search and find all .PDF files? but “how can i find this with powershell”

we can

let try it ..

Cmdlet Used: Get-ChildItem,Group-Object, Sort-Object

Command: $files =  Get-ChildItem -Path C:\Users\aman.dhally\Documents –Recurse

In $files variable i am saving the result of Get-ChildItem -Path C:\Users\aman.dhally\Documents –Recurse  command , Get-ChildItem in equal as DIR command and we are using –Path switch parameter to give the path of the folder in which we want to search for files, –Recurse means including sub folders.

File

lets run $files variable and see what it has stored

It showing the files and folders located in my “Document” folder

File_2

let filer the results

$files | Group-Object -Property Extension | Sort-Object Count –Descending

now pipe the $files variable to Group-Object cmdlet and the grouping Property is Extensions because we want to group files by there extensions, now piped the command to Sort-Object and we are sorting the results by Count,

OoPs 751 .torrent files,, going to delete them . )

File_3 

Thanks

aman dhally

Thursday, November 24, 2011

Finding Network Adapter Data Based On Connection Name

 

PowerTip of the Day, from PowerShell.com

Sometimes it would be nice to be able to access network adapter configuration based on the name of that adapter as it appears in your Network and Sharing Center. To find the network configuration data for any network card with a "LAN" in its name, use this code:

Get-WmiObject Win32_NetworkAdapter -Filter 'NetConnectionID like "%LAN%"' |   ForEach-Object { $_.GetRelated('Win32_NetworkAdapterConfiguration') }

If you want to further narrow this down and cover only NICs that are currently connected to the network, extend the WMI filter:

Get-WmiObject Win32_NetworkAdapter -Filter '(NetConnectionID like "%LAN%") and (NetConnectionStatus=2)' |   ForEach-Object { $_.GetRelated('Win32_NetworkAdapterConfiguration') }


Tuesday, November 22, 2011

How to find “Stopped” windows Services, whose start up mode is set to “Automatic” using PowerShell.


Hi,
I called these services as “Problematic services”. The start-up mode of these services are “Automatically” so that whenever windows starts or reboot these services should start automatically.
So logically if any of windows services start mode is set to “Automatic” then the Window Service should be running not “stopped”
we are using WMI query language to find these “Problematic Services”
Cmdlet use: Get-WmiObject, Where-Object , Select-Object, Format-List
we are using Win32_Service WMI call to retrieve the list  and status of the services.
   1: Get-WmiObject win32_Service

above command will show the list of all windows services.

Service_1

Let’s check the all properties of a single “Service”

Get-WmiObject win32_Service  | select -First 1 | fl *

we are piping the result of “Get-WmiObject win32_service” to select-Object cmdlet and choosing -first 1 single Service and then piping further to “Format-List” cmdlet and using * wildcard to show everything.

In below properties we are interested in Name,Status, StartMode, and State property of services.

Service_2
Get-WmiObject win32_Service  | where {$_.StartMode -eq "Auto" -and $_.State -eq "stopped"}


we are piping the previous command to Where-Object cmdlet and filtering to show  only those services whose “StartUp” mode is “Automatic” and “Status” is “Stopped”

oh!!! we have three problematic services. Okkk!!!

Service_3

Let’s filter a little bit more
Get-WmiObject win32_Service  | where {$_.StartMode -eq "Auto" -and $_.State -eq "stopped"} |  Select Name,StartMode,State


now we are piping all the previous command to Select-Object cmdlet and choose to show only Name, StartMode, and State property.

Now it seems little bit formatted.

Now you can start these service manually .

Service_4

Thanks

Aman Dhally

Outputting Text Reports without Truncating

 

PowerTip of the Day, from PowerShell.com:

If you want to capture PowerShell results in a text file, you can redirect the results or pipe them to Out-File. In any case, what you capture is the exact representation of what would have been displayed in your PowerShell console. So, depending on the amount of data, columns may be missing or truncated.
Here is a function called Out-Report. You can pipe any result to it to create a text file that does not truncate columns. In addition, with the –Open switch parameter, you can open the resulting text file, too:
   1: function Out-Report {
   2:  
   3:  param(
   4:  
   5:   $Path = "$env:temp\report.txt",
   6:  
   7:   [switch]$Open
   8:  
   9:  )
  10:  
  11:  
  12:  
  13:  $Input |
  14:  
  15:   Format-Table -AutoSize |
  16:  
  17:   Out-File $Path -Width 10000
  18:  
  19:  
  20:  
  21:   if($Open) { Invoke-Item $Path }
  22:  
  23: }

Try it:

Get-Process | Out-Report -Open

Thanks

Aman

Monday, November 21, 2011

I know its funny :)

 

total Page views are: 420  :D

 

Funny-420 visitors

Find the List of Installed software using WMI and PowerShell.

 

Hi,

how you find the which software is installed on your computer, most of users answered  in “Control Panel” , yes it is right . but, if you are creating an Inventory of which system have which software then it’s not so useful for admins.

lets use WMI to retrieve the list of Install list of Softwares:

Cmdlet used: Get-WmiObject, Select-Object, Sort-Object, Export-CSV

Command is:

   1: Get-WmiObject win32_Product  | Select Name,Version,PackageName,Installdate,Vendor | Sort InstallDate -Descending

using Get-WmiObject cmdlet we query the win32_Product class which have the information of list of all software installations. Then we piped the command to Select cmdlet and we are selecting Name, Version, PackageName and installation date of the softwares and then pipe the command to Sort-Object cmdlet and sorting the result to descending order which mean latest first.


Software-1


let export the result to CSV for future reference using Export-CSV cmdlet.



   1: Get-WmiObject win32_Product  | Select Name,Version,PackageName,Installdate,Vendor | Sort InstallDate -Descending| Export-Csv d:\report.csv

 


all command is same but we piped the command further to Export-CSV cmdlet and saving the file to D:\ with name of Report.CSV


Software-2 





let see if this created a csv file .


Software-3


yes, file is created lets open it!!!


Done !!! seems good isn’t.


Software-4


 



Thanks for viewing


Aman Dhally

Sunday, November 20, 2011

Turning SIDs into Real Names using PowerShell

 

PowerTip of the Day, from PowerShell.com:

Sometimes, you'd like to turn security identifiers (SIDs) into real names. Here is a function that can do this for you:

   1: function SID2Name($sid){
   2:  
   3:   $objSID = New-Object System.Security.Principal.SecurityIdentifier($sid)
   4:  
   5:   try {
   6:  
   7:   $objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
   8:  
   9:   $objUser.Value
  10:  
  11:   } catch { $sid }
  12:  
  13: }

And, here is a show case for the function: to enumerate all profiles on your computer, you can read them from the Registry. However, all profiles are stored with SIDs only. Thanks to your new function, you can now display the real user names of everyone who has a profile on your machine:



   1: function Get-Profile {
   2:  
   3: $key = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
   4:  
   5: dir $key -Name | ForEach-Object { SID2Name $_ }
   6:  
   7: }


Thanks to www.Powershell.com

Friday, November 18, 2011

Converting User Names to SIDs using PowerShell

 

PowerTip of the Day, from PowerShell.com: 

Converting User Names to SIDs

If you want to translate a valid user name to its security identifier (SID), here is a function to do that for you:

 

Converting User Names to SIDs

If you want to translate a valid user name to its security identifier (SID), here is a function to do that for you:

function Name2SID($name, $domain=$env:userdomain) {

$objUser = New-Object System.Security.Principal.NTAccount($domain,$name)

$strSID =$objUser.Translate([System.Security.Principal.SecurityIdentifier])

$strSID.Value

}

Try it with your current user name:

 

Name2SID $env:username

 

Note: Tip copied from PowerShell.com

Copy Files and Folders using PowerShell

 

 

Hi,

Copy files and folders this is the task which every Admin or even a end user performs daily.

How we can Copy files and folder using PowerShell?

Quite Easy, we just need to use Copy-Item cmdlet with few Switch Parameters that all.

Cmdlet used : Copy-Item

:::: Copy Files

Lets create a a new folder to Backup files currently I have  one Folder named “Folder_A” which contain Data and we will create a new folder named as “Backup_A” , and then copy data from “Folder_A” to “backup_A”

Files-1

let create a new folder named “Backup_A”

Files-2

Now we have two folders “Folder A” and “Backup_A”

Files-3

now copy a file from “Folder_A” to “backup_A” ,

command is: Copy-Item D:\Demo\Folder_A\Book.txt -Destination D:\Demo\Backup_A

file successfully copied.

Files-4

:::: Copy Txt file only

-Include

if we want to copy specific type of files only then we can use –Include switch Parameter followed by the type .

-Verbose 

We can use –Verbose switch to see which files are getting copied

command: Copy-Item D:\Demo\Folder_A\* -Destination D:\Demo\Backup_A -Include *.txt –Verbose

see the screenshot, command copied the .Txt files only

Files-5

:::: Exclude files to copying

-Exclude

If we are using Copy-Item cmdlet in a backup script it would be good we don’t backup Music,Video files on server. As a Ideal Policy we should not fill our SAN, Server storage with the backup of users music and videos.

to exclude these files to be copied use –Exclude switch parameter followed by file types example *.mp3,*.mp4 etc

in my Folder_A i have few MP3 audio and few MP4 video files, lets stop them copying to our Backup_A folder.

Files-6

note: * means all

Command: Copy-Item D:\Demo\Folder_A\* -Destination D:\Demo\Backup_A -Exclude *.mp3,*.mp4

When i search for *mp3 and  *mp4 no result were found and you can also see there is not a single MP3 and MP4 in “Backup_A” folder.

Files-7

:::: Copy Folders

the command is same like copying file but rather then specify file we need to specify folder

Command : Copy-Item D:\Demo\Folder_A\Recurse_Testing -Destination D:\Demo\Backup_A\

Folder Copied

Files-8

BUTTTTTTTT !!! wait…!!!!!!!!!!!!!

Check the folder again, Recurse_Testing have some Sub-folders which are not copied in backup_A

Files-9

-Recurse

to Copy All folder including sub-folders use –Recurse while copying

Command is:

Copy-Item -Recurse D:\Demo\Folder_A\Recurse_Testing -Destination D:\Demo\Backup_A\  -Verbose

Files-10

let check if it copied subfolder also.

Seems Identical isn’t.

Files-11

:::: Copy all files and Folders

To copy all file and folder we use * wildcard which means all , and –Recurse to copy sub-directories also and we also use –force do that if there any file exists with same name on backup folder it should get overwrites.

command : Copy-Item -Recurse D:\Demo\Folder_A\* -Destination D:\Demo\Backup_A -Force –Verbose

Files-12

lets check if these two folders are identical.

Seems like TWINS isn't ;-)

Files-13

Hope it is useful to someone .

Thanks

Aman Dhally

Thursday, November 17, 2011

Use PowerShell as “Calculator”

 

Hi,

this is a very basic tip.

The tip is “You can use PowerShell as a calculator”, so guys stop using CALC use PowerShell instead.

I don’t teach you how to use Addition (+), Subtraction (-), Multiplication (*) and Division (/), tried it yourself :)

CalcuLator

 

Thanks

Aman

Wednesday, November 16, 2011

“VIM” a console based Script Editor for PowerShell

 

Hi,

I hope some of you know about what is VIM is and for those who don’t know what VIM is for them “VIM” is console based text editor and it’s very advance text editor. Basically VIM was made for LINUX and it’s come pre-installed in most of the Linux Distributions. Now they also make it compatible with Windows. You can download VIM executable from VIM website or you can download VIM directly from this Download link ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip 

Why to use VIM?

hummm.. if you want to do edit PowerShell scripts directly from PowerShell Console or you don’t want to use EDIT command to edit PowerShell Script and want some more advance features then VIM is for you. We will use VIM as console based test Editor.

How to use it?

Download vim  ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip  and save it anywhere on your laptop and Extract the .ZIP file.

Vim-0

Now Paste the extracted Vim.exe folder in C:\Windows\System32 so that it automatically added to your environmental path so that we can execute the VIM.exe from anywhere in the console.

Vim-1

Now lets open PowerShell Console and see if we able to run VIM successfully.

Vim-2

It’s Open.. to quit this windows type :q

Vim-3

Now open a PowerShell Script using VIM , Vim  and location of PowerShell Script

Vim-4

Looks good isn’t

Vim-5

Press Escape and type :se nu in vim and hit Enter and Line Number appear in the script :)

Vim-7

to quit the vim without saving the script Press Escape Key and type :q! and hit enter.

To know more about vim see this online documentation : http://vimdoc.sourceforge.net/htmldoc/usr_toc.html 

 

Thanks for reading

 

Aman Dhally

Tuesday, November 15, 2011

Ping Multiple Servers using “PowerShell”

 

Hi,

Today I was looking for  a little PowerShell script which can Ping multiple servers and give a consolidated view on PowerShell console that which one is Live and which one is Dead.

Then a decide to write my own and finally wrote  it: ) and it is a only a 9 line script :)

You can copy and paste the script from below or you can download it from here : http://dl.dropbox.com/u/17858935/Ping_Multiple_Servers.zip 

let me explain the script :

$Servername: is a variable which contain a list  of comma separated Server name

in foreach script block we are selecting all servers in $ServerName variable and run Test-Connection cmdlets against them

in If Test-Connection evaluates that servers in Pinging that it writes “S$server is alive” otherwise it write “Server is dead”,

In test-connection Cmdlet we define that it should send only 2 Pings to the server using –count 2 switch parameter and used –Quiet Switch parameter so that is show the output in Boolean (true or false)

 

   1:  #### Provide the computer name in $computername variable
   2:   
   3:  $ServerName = "Dc-2","LocalHost","Server-2","Not-Exists","Fake-computer"
   4:   
   5:  ##### Script Starts Here ###### 
   6:   
   7:  foreach ($Server in $ServerName) {
   8:   
   9:          if (test-Connection -ComputerName $Server -Count 2 -Quiet ) { 
  10:          
  11:              write-Host "$Server is alive and Pinging " -ForegroundColor Green
  12:          
  13:                      } else
  14:                      
  15:                      { Write-Warning "$Server seems dead not pinging"
  16:              
  17:                      }            
  18:  }
  19:   
  20:  ########## end of script #######################



The output of the script will be like below link.


Ping


 


Download Link : http://dl.dropbox.com/u/17858935/Ping_Multiple_Servers.zip 


 


Thanks


aman dhally

Monday, November 14, 2011

How to create and change “Windows Registry Keys” using PowerShell.

 

Hi,

The Best thing about PowerShell is that you can manipulate “windows  Registry Keys” very easily with it. How? Let me show to you.

Why we need to create a registry Hive/key manually?

Actually for lots of reason, for example if you want to install some particular software on all accounting computer automatically and then you can need write a script which check the predefined registry Keys and if it found that the in key  Department is “accounts” then install it may install some accounting software on it otherwise don’t do anything.

Cmdlets used: New-Item , New-ItemProperty, Set-ItemProperty

Before running the below command  make sure you run PowerShell as Administrator.

How to run PowerShell as Administrator?

to do this , Search for PowerShell { you can also access the same from Start > All Programs > Accessories > windows PowerShell > Windows PowerShell} , Right Click on it and Choose “Run as Administrator

Registry-A

When you run PowerShell as Administrator you will see that the title bar of PowerShell windows shows Administrator:

Registry-0

Now let’s create a new Folder named “CompanyName” in “Hkey_Local_machine” and  beneath Software key folder.

In PowerShell we can use Registry hives as Local drives so we can use New-item cmdlet to create a new registry hive.

new-Item -Name "CompanyName"  -Path 'hklm:\SOFTWARE\'  -type Directory

New-Item : used to create a new folder for file

-Name : Name of the Folder

-Path: where we want to create a new folder

-Type: Directory in our case because “CompanyName” will contain some sub registry keys.

Registry-1

Let’s  check . . . Yes “Registry Hive” is created . .

Registry-2

now lets create a new Registry key in “ComanyName”  names as “Department” which have some information about which on Department the laptop/desktop belong to.

New-ItemProperty -Path 'hklm:\software\CompanyName\' -Name "Department" -Value "I.T"

Registry-3

Let’s check ….. Key is created . . . .

Registry-4

okies..

what if you need to change the value of the key?, you can do it easily using Set-ItemProperty cmdlet.

Now Lets change the department name from “I.T.” to “Accounts”

set-ItemProperty -Path 'hklm:\software\CompanyName\' -Name "Department" -Value "Accounts"

 Registry-5

Let’ See…….yes Department name is changes from “I.T.” to “Accounts”

Registry-6

 

I hope this post will save someone time :) ..

Thanks

Aman Dhally

www.amandhally.net/blog