使用powershell脚本重启机器

时间:2020-12-31 12:56:24

标签: powershell powershell-2.0 powershell-3.0 powershell-4.0

我正在运行以下代码,但重新启动不起作用。我的目的是一次在所有远程机器上并行运行重启命令。

$YourFile = gc "machinelst.txt"
$username = "user1"
$password = "pass1"
$secpw = ConvertTo-SecureString $password -AsPlainText -Force
$cred  = New-Object Management.Automation.PSCredential ($username, $secpw)

foreach ($computer in $YourFile)
{
    Invoke-Command -ComputerName $computer -credential $cred -ErrorAction Stop -ScriptBlock { Restart-Computer -ComputerName $computer -Force } -AsJob
     
} 

enter image description here

3 个答案:

答案 0 :(得分:1)

这看起来像是 Get-Job 的输出 - 你能试试 Receive-Job $id (Receive-Job 80)。

应该给你真正的例外。

答案 1 :(得分:1)

这可能是并行运行的,就像 invoke-command 处理计算机名数组一样:

restart-computer computer01,computer02,computer03,computer04,computer05

或者这个。 winrm 服务需要几分钟才能恢复,但它们似乎都在同一时间重新启动。

$c = get-credential
$list = 1..10 | % tostring computer00
restart-computer $list -wait -protocol wsman -cr $c

答案 2 :(得分:0)

试试这个(如果可行,您可以添加 -asjob):

$username = "yourdomain\user1"
$password = ConvertTo-SecureString "pass1" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

get-content "machinelst.txt" | %{
Restart-Computer -ComputerName $_ -Authentication default -Credential $cred

}

如果你想使用工作,你可以这样做:

$listjob=@()

get-content "machinelst.txt" | %{
$listjob+=Restart-Computer -ComputerName $_ -Authentication default -Credential $cred -AsJob
}

$listjob | Wait-Job -Timeout 30

$listjob | %{

    if ($_.State -eq 'Failed' )
    {
      Receive-Job -Job $_ -Keep
    }
   
}
相关问题