如何将拒绝访问权限和Powershell中的所有其他错误重定向到变量(循环直到命令不失败)

时间:2015-06-16 16:21:30

标签: powershell powershell-v3.0

我正在尝试创建一个引导脚本来设置服务器并将它们添加到域中。问题是某些网络更改未在不同的时间内实现,导致命令加入域失败(始终具有相同的错误)。为了解决这个问题,我只需要在一分钟后再次运行该命令,但这对于长脚本来说是不切实际的。

我的解决方案是:

$exit = 1
while ($exit -ne 0){
    $exit = 0
    join-domain-command
    $exit = $?
    sleep 20
}

然而,即使我输入一些必然会失败的不存在的命令,$ exit总是为0 / false。

我的另一个想法是将所有错误重定向到变量并在变量中搜索包含我经常遇到的错误的文本,如果该错误不存在,请停止循环。

尝试在powershell中重定向stderr对我来说不起作用

$exit = & (dummy-command -confirm:$false) 2>$exit
echo "exit = $exit"

所以我在这里故意将ExecPol置于一个不提升的提示中:

No Exit Code

2 个答案:

答案 0 :(得分:1)

你可以使用-errorvariable

$exit = 1
while ($exit -ne 0){
    $exit = 0
    join-domain-command -errorvariable $error
    $exit = $?
    sleep 20
}

或者如果你想对错误做些什么:

    try {
    join-domain-command -errorvariable $error
    }
    catch{
    $error | out-file C:\errors.txt -append
    #or if $error -contains "something" 
    #...do something
    }

然后在文本文件中搜索您的错误

修改

实际上正确使用errorVariable的一些事情并没有使用$所以它会-errorvariable myError

如果您想要搜索错误,更好的方法是:

while ($exit -ne 0)
{ 
try {
    join-domain-command
    }
catch{
    if(!($error[0].tostring().contains("specific error text"))) #error text is not your specific error
      {$exit = 1}
    }
sleep 20
}

可以在$error中找到所有错误,如果您想检查上次使用的$error[0]错误,它会为您提供上次收到的错误。

答案 1 :(得分:0)

我通常做类似下面的事情,我把它放在一个单独的函数中,以保持主代码路径的清洁。可以添加一个计数器来限制重试次数。

$Succeeded = $false
while($Succeeded -eq $false){

  try{
    #commands that may fail
    $Succeeded = $true
  }
  catch{
    #write a message or log something
  } 
  start-sleep -s 60
}