Nebelz Cheez
Nebelz Cheez

Reputation: 307

Reboot AD computers one at a time through powershell

I need to reboot all computers in AD one at a time(excluding my computer), confirming that each one has restarted before restarting the next one. Once a system has rebooted, I want to see it's IP address and name. Below is my attempt but I think I'm doing something wrong since its not working. The main error I receive is:

 Get-WMIObject: cannot validate argument on parameter 'computerName'. The argument is null or empty
 + $serverobj = gmi Win32_operatingsystem -computername $i.server

Code:

$servers= Get-ADComputer -Filter * | Select-Object -ExpandProperty name

foreach($i in $servers) {
 Write-Host "Rebooting:" $i.server "..."

 $serverObj = gwmi Win32_operatingsystem -computer $i.server

 $status = $serverObj.reboot()

 if ($status.ReturnValue = "0") {
      Write-Host "Reboot successful."
 } else {
      Write-Host "Reboot failed."
 }
do {
    Start-Sleep -s 2 }  # this will wait for 2 seconds 
while (Test-Connection $servers -count 1 | select @{Name="Computername";Expression={$_.Address}},Ipv4Address)
}

Upvotes: 0

Views: 1012

Answers (1)

Matt
Matt

Reputation: 46710

This one seems simple enough for your immediate problem:

$serverObj = gwmi Win32_operatingsystem -computer $i.server

should be

$serverObj = gwmi Win32_operatingsystem -computer $i

$i has no properties beyond what a [string] has. PowerShell, by default, will allow you to attempt to get properties that do not exist and a null will be returned in that case. Get-WMIObject however cannot work with that for the parameter -Computer. The error was pretty specific.

There is a way you can try and catch these issues but using Set-StrictMode -Version 2.0 for example. From TechNet

2.0

-- Prohibits references to uninitialized variables (including uninitialized variables in strings).

-- Prohibits references to non-existent properties of an object.

-- Prohibits function calls that use the syntax for calling methods.

-- Prohibits a variable without a name (${}).


You refer to the main error you are receiving ... does that mean you have more?

Your while condition seems flawed. You should be trying to evaluate a boolean expression but you are just returning data. Even if the ping failed data should be returned and that could invalidate the logic of your loop. Consider using the switch -Quiet for test-connection. You are also checking the pings of all $servers instead of just $i.

while (!(Test-Connection $i -count 1 -Quiet))

maybe...

Upvotes: 4

Related Questions