Easy way to interact with several servers remotely using Powershell


Easy way to interact with several servers remotely using Powershell.
The following lines restart the first 10 servers from a server farm that are using similar naming convention:

1..10 | % {$i=”{0:0}” -f $_;$server = “srv-prod$i”; invoke-command -computername $server -scriptblock { shutdown /r /t 0 }}
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-dev$i”; invoke-command -computername $server -scriptblock { shutdown /r /t 0 }}
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-cert$i”; invoke-command -computername $server -scriptblock { shutdown /r /t 0 }}
 

The following lines disable a scheduled task (ScheduledTask1 and ScheduledTask2) from the first 10 servers in prod and dev while enabling ScheduledTask3 on cert environment:

1..10 | % {$i=”{0:0}” -f $_;$server = “srv-prod$i“; invoke-command –computerName $server -scriptblock { schtasks /Change /TN ScheduledTask1 /Disable }}
 
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-dev$i“; invoke-command –computerName $server -scriptblock { schtasks /Change /TN ScheduledTask2 /Disable }}
 
1..10 | % {$i=”{0:0}” -f $_;$server = “srv-cert$i“; invoke-command –computerName $server -scriptblock { schtasks /Change /TN ScheduledTask3 /Enable }}
 
The following script retrieves the up-time in seconds of a specific service (in this case Netlogon). The script verifies the service state on several machines at the same time:
 
PS C:\Users\dan.popescu> 1..10 | % {$i=”{0:0}” -f $_;$server = “srv$i”; invoke-command -computername $server -scriptblock {$services = gwmi -class win32_service | ? {$_.name -like “Netlogon”};$hostname = “$env:computername.$env:userdnsdomain”.ToLower();write-host $hostname;foreach ($service in $services){$uptime = “{0:N2}” -f ((get-date) – (Get-Process -Id $service.processId ).starttime).totalhours; $info = @{Service = $Service.name; Uptime = $uptime};$results = New-Object -TypeName PSObject -Property $info; write-host $results}}}
If you cannot run these commands remotely it means that the Windows Remote management service does not run on the target machine. Open a Powershell prompt and type winrm quickconfig and follow the on-screen instructions. Once the service is configured, you will be able to run the scripts:
Windows Remote management service
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s