Shutting down multiple PCs remotely

0

i want to shut down almost all PCs at my workplace (if they run more than 2 days) I've worked the last and this week on a Script and trying to get rid of Errors on the way.

$days = -0
$date = (get-date).adddays($days)
$lastboot = (Get-WmiObject Win32_OperatingSystem).LastBootUpTime
$Computer = Get-ADComputer -SearchBase 'OU=______,OU=______,DC=______,DC=______' ` -Filter '*' | Select -EXP Name

$lastbootconverted = ([WMI]'').ConvertToDateTime($lastboot)

write-host $date

write-host $lastboot

write-host $lastbootconverted

if($date -gt $lastbootconverted)
{
write-host Need to reboot
(Stop-Computer -$Computer -Force)
}
else
{
write-host no need to reboot
}

When I run it it says "The RPC-Server isn't available. (Exception HRESULT: 0x800706BA)" But if I just put a PC Name instead of the "$Computer", it shuts the PC down like I want. What is this RPC-Server Error? I don't have a firewall activated, so I'm clueless...

The OU=_____ and DC=______ are private company names

powershell
shutdown
asked on Stack Overflow Oct 4, 2016 by Gunter

1 Answer

0

I've got not AD environment to test your Get-ADComputer query, but this worked for me with just an array of computer so should be fine for you.

function Get-LastBootUpTime {            
param (
    $ComputerName
)
    $OperatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName               
    [Management.ManagementDateTimeConverter]::ToDateTime($OperatingSystem.LastBootUpTime)            
}

$Days = -2
$ShutdownDate = (Get-Date).adddays($days)

$ComputerList = Get-ADComputer -SearchBase 'OU=______,OU=______,DC=______,DC=______' ` -Filter '*' | Select -EXP Name

$ComputerList | foreach {
    $Bootup = Get-LastBootUpTime -ComputerName $_

    Write-Host "$_ last booted: $Bootup"

    if ($ShutdownDate -gt $Bootup) {
        Write-Host "Rebooting Computer: $_" -ForegroundColor Red
        Restart-Computer $_ -Force
    }
    else {
        Write-Host "No need to reboot: $_" -ForegroundColor Green
    }
}
answered on Stack Overflow Oct 4, 2016 by James C. • edited Oct 11, 2016 by James C.

User contributions licensed under CC BY-SA 3.0