【问题标题】:PowerShell remote PC shutdown, single PCPowerShell远程PC关机,单台PC
【发布时间】:2016-10-07 09:47:43
【问题描述】:

OU=_ 是私人公司名称。我知道它是重启,这只是在它进入真正的关闭过程之前进行测试。

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

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

$ComputerList = Get-ADComputer -SearchBase 'OU=TEST-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 $Computer -Force
    }
    else {
        Write-Host "No need to reboot: $_" -ForegroundColor Green
    }
}

我正在尝试关闭公司中运行时间超过 2 天的所有 PC。脚本已经完成了,但是当涉及到这一点时它会显示一个错误:

restart-Computer $Computer -Force

如果我键入而不是 $Computer, $ComputerList 脚本会关闭该 OU 中的每台 PC,即使它们运行时间不超过 2 天。 所以只需要一台 PC 运行超过 2 天就可以关闭整个公司,这不是我想要的。 当它们已经运行超过 2 天时,我如何告诉脚本仅关闭 PC?

【问题讨论】:

    标签: powershell shutdown


    【解决方案1】:

    您的$Computer 未定义。你应该使用:

    Restart-Computer $_ -Force
    

    但更好的方法是在一个变量中收集所有应该重新启动的计算机,然后完全重新启动它们。会工作得更快:

    $toBeRestarted = $ComputerList | Where-Object { $ShutdownDate -gt (Get-LastBootUpTime -ComputerName $_) }
    Restart-Computer $toBeRestarted -Force
    

    如果您愿意,可以添加更多日志记录

    【讨论】:

    • 我刚刚解决了Restart-Computer $_ -Force,我认为它可以工作。我没有及时测试它,因为我要关闭的电脑在线时间不够长,但周一我会更彻底地测试它。如果它不起作用,我将尝试您的其他解决方案,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多