Powershell脚本停止过程并继续

时间:2018-09-04 13:05:41

标签: powershell

我有一个脚本,在其中我在计算机列表上运行shutdown.exe命令。该脚本可以正常运行,直到由于某种原因挂起为止。

有没有一种方法可以“ ctrl + c”关闭命令,然后继续处理下一台PC。

这是即时通讯所使用的。

buttonRestartWorkstations_Click={
#TODO: Place custom script here

$online = $checkedlistbox1.CheckedItems | where { Test-Connection -
ComputerName $_ -Count 1 -Quiet }

$computercount = $online.Items.Count

$progressbar1.Maximum = $online.Count
$progressbar1.Step = 1
$progressbar1.Value = 0

foreach ($computer in $online)

{
    $progressbar1.PerformStep()
    shutdown -r -t $textbox3.Text -m $computer
    Start-Sleep -s 1

}
$label2.Visible = $true
$label2.Text = "Selected Servers will reboot on the " + $textbox1.text

1 个答案:

答案 0 :(得分:0)

Restart-Computer cmdlet将使您能够并行定位多台计算机,而一台计算机上的问题不会影响另一台计算机上的执行。

如您所说,Restart-Computer不是您的选择,因为您希望在给定计算机上启动重新启动之前有一个 delay shutdown -r -t <secs>给您;请注意,尽管Restart-Computer确实有一个-Delay参数,但其用途有所不同。

如果

  • 您的目标计算机设置为PowerShell remoting
  • ,您可以运行脚本提升(具有管理权限)

您可以使用Invoke-Command并行定位计算机,然后在其上本地运行shutdown.exe(PSv3 +语法):

$delay = $textbox3.Text
Invoke-Command -ComputerName $online { 
  shutdown -r -t $using:delay
  "$(('FAILED to initiate', 'Successfully initiated')[$LASTEXITCODE -eq 0]) reboot on $env:COMPUTERNAME."
} | ForEach-Object { $progressbar1.PerformStep() }

就像您的原始代码一样,一旦重启启动,每台目标计算机上的执行都会返回,尽管执行会并行发生,并且从不保证目标计算机的输入顺序。

如果您想验证并等待成功重启,则需要做更多的工作。

所有错误均以红色显示在控制台上,以后可以在$Error集合中进行检查。

请注意,"$(('FAILED to initiate', 'Successfully initiated')[$LASTEXITCODE -eq 0]) reboot on $env:COMPUTERNAME."的主要目的是在每台计算机上无条件产生 some (无错误)输出,以便为每台计算机调用ForEach-Object脚本块( shutdown默认不产生stdout输出,ForEach-Object不会对stderr输出起作用。

相关问题