远程关闭多台电脑

Shutting down multiple PCs remotely

我想关闭我工作场所几乎所有的电脑(如果它们 运行 超过 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
}

当我 运行 它说 "The RPC-Server isn't available. (Exception HRESULT: 0x800706BA)" 但是,如果我只是输入一个 PC 名称而不是“$Computer”,它就会像我想要的那样关闭 PC。这个 RPC 服务器错误是什么?我没有激活防火墙,所以我一无所知...

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

我没有 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
    }
}