从Powershell中的try/catch恢复变量

从Powershell中的try/catch恢复变量,powershell,Powershell,我在重新启动脚本时遇到问题。我试图向一系列服务器发送重启计算机命令,并捕获故障,以便以另一种方式重试(在本例中,通过VIC) 这是我的代码片段 try { Restart-Computer -ComputerName $_.Servername -Credential $cred -Force -ErrorAction Stop } catch [system.exception] { #Create output object $output = [pscust

我在重新启动脚本时遇到问题。我试图向一系列服务器发送重启计算机命令,并捕获故障,以便以另一种方式重试(在本例中,通过VIC)

这是我的代码片段

try {
    Restart-Computer -ComputerName $_.Servername -Credential $cred -Force -ErrorAction Stop
    }
catch [system.exception] {
    #Create output object
    $output = [pscustomobject] @{
        Servername = $_.Servername
        Domain = $_.Domain
        Environment = $_.Environment
        VIC = $_.VIC
        }
    Export-Csv -InputObject $output -Path C:\temp\VICredo.csv -Force -NoTypeInformation
    }
}

这里的问题是$u变量并没有到达catch块,所以我无法将它们写入“重试列表”。有人能想出一种可行的方法吗?

当遇到终止错误时,原始管道将停止。启动了另一条管道,该管道中存在错误


您可以通过切换到使用foreach循环来解决这一问题。

您可以始终将
$\uucode>分配给专用变量,并在整个
try
/
catch
块中使用该变量:

... | ForEach-Object {
  try {
    $comp = $_
    Restart-Computer -ComputerName $comp.Servername ...
  } catch [System.Exception] {
    #Create output object
    $output = [PsCustomObject] @{
      Servername  = $comp.Servername
      Domain      = $comp.Domain
      Environment = $comp.Environment
      VIC         = $comp.VIC
    }
    Export-Csv ...
  }
} | ...
或者,按照建议,您可以使用
foreach
循环:

foreach ($comp in ...) {
  try {
    Restart-Computer -ComputerName $comp.Servername ...
  } catch [System.Exception] {
    #Create output object
    $output = [PsCustomObject] @{
      Servername  = $comp.Servername
      Domain      = $comp.Domain
      Environment = $comp.Environment
      VIC         = $comp.VIC
    }
    Export-Csv ...
  }
}

foreach
循环的缺点是,如果不将循环放入子表达式中或首先将其输出赋值给变量,就无法将其输出传递到管道中。

这是当前foreach循环中的一部分,我只是遗漏了很多内容,因为它包含的信息比需要的更多。您是指try/catch中的foreach循环吗?不,foreach(){}与foreach对象{}相反。您可以使用子表达式-$(foreach($i in$a){})使foreach循环与管道一起工作。不需要中间变量。@mjolinor啊,是的。我忘了。好的。非常感谢你们俩。我从未真正理解foreach和foreach对象的区别。这很有帮助。