远程关闭多台PC

时间:2016-10-04 13:13:32

标签: powershell shutdown

我想在我的工作场所关闭几乎所有的PC(如果它们运行超过2天) 我已经完成了最后一周和本周的脚本工作,试图在路上摆脱错误。

$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
}

当我跑它时,它说 " RPC-Server不可用。 (Exception HRESULT:0x800706BA)" 但是,如果我只是放置一个PC名称而不是" $ Computer",它会像我想要的那样关闭PC。什么是RPC-Server错误?我没有激活防火墙,所以我一无所知......

OU = _____和DC = ______是私人公司名称

1 个答案:

答案 0 :(得分:0)

我没有AD环境来测试你的Get-ADComputer查询,但这对我来说只有一个计算机阵列,所以应该没问题。

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
    }
}