【问题标题】:Restart machine using powershell script使用 powershell 脚本重启机器
【发布时间】:2020-12-31 12:56:24
【问题描述】:

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

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

【问题讨论】:

  • 删除 -ErrorAction Stop 读取错误
  • 感谢您的回复,我已删除 -ErrorAction Stop 并再次运行脚本。它没有重新启动
  • 你的错误文本是什么
  • Id 名称 PSJobTypeName 状态 HasMoreData 位置命令 -- ---- ------------- ----- ------------ -------- ------- 76 Job76 RemoteJob 失败 False RemoteHost1 Restart-Computer -Com... 78 Job78 RemoteJob 失败 False RemoteHost2 Restart-Computer -Com... 80 Job80 RemoteJob 失败 False RemoteHost3 Restart -Computer -Com...这是输出
  • 删除 -AsJob 并告诉我你的错误

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


【解决方案1】:

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

应该给你实际的例外。

【讨论】:

    【解决方案2】:

    这很可能是并行运行的,就像 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
    

    【讨论】:

      【解决方案3】:

      试试这个(如果可以的话,你可以添加 -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
          }
         
      }
      

      【讨论】:

      • ConvertTo-SecureString :输入字符串的格式不正确。在 restart.ps1:14 char:26 $password = "pass1" | ConvertTo-SecureString
      • 试试这个改变
      • 好的,现在好像可以工作了。我想知道的一件事,这个脚本将同时在所有远程服务器上执行重启?还是会按顺序运行?。
      • 您可以使用“-asjob”命令来启动并行重启,但重启都需要时间,具体取决于远程服务器。我认为可能会有几秒钟的间隙。
      猜你喜欢
      • 2022-10-18
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 2021-11-19
      相关资源
      最近更新 更多