Powershell Try& Catch在try中运行多个命令

时间:2013-05-08 19:12:44

标签: powershell try-catch powershell-v2.0

您好我想弄清楚如何做到这一点或其他方式

try {
Get-ADComputer -Identity namedoesnotexist
(Get-ChildItem).FullName
}
catch {$_ | Out-File log.log}

运行此代码时,我使用的名称不存在,因此我收到错误,catch会将此内容写入我的日志文件(只是一个示例) 我想要完成的是错误被捕获但是try语句继续运行我的Get-Childitem命令并尝试它。 还有其他简单的方法吗?

1 个答案:

答案 0 :(得分:1)

在try..catch中只放一行就会产生效果

try 
{
  Get-ADComputer -Identity namedoesnotexist
}
catch 
{
  $_ | Out-File log.log
}
(Get-ChildItem).FullName

但也许trap正是你要找的东西

trap
{
  $_ | Out-File log.log
  continue # remove this if you still want to see each error
}
Get-ADComputer -Identity namedoesnotexist
(Get-ChildItem).FullName