Search code examples
powershellhardcode

How can I hardcode specific server names in powershell script


I want to reboot specific servers, I am using findstr to find specific servers in the list of 1000's of servers, however, is there any way I can hardcode servernames in a script so the script only run on a particular set of remote servers? Also, how to use for each against array variable. For e.g is below method correct?

$serverlist = "server1,server2,server3"

for each ($server in $serverlist){  $serverboot= gwmi win32_operatingsystem -comp $server
$serverboot.Reboot
}

Solution

  • First define a list of your servers for this the coma (,) is the array operator in PowerShell :

    $serverlist = "server1","server2","server3"
    

    Now $serverlist is an array or a collection you can use.

    Then you pipe this list in the Foreach-Object Cmdlet that allow you to execute a scriptblock for each element in the list. $_ represent the current element. ; is the instruction seprator :

    $serverlist | ForEach-Object {$serverboot= gwmi win32_operatingsystem -comp $_; $serverboot.Reboot()}