gpt4 book ai didi

PowerShell:使用 Invoke-Expression 管理错误

转载 作者:行者123 更新时间:2023-12-03 14:10:29 26 4
gpt4 key购买 nike

我试图弄清楚如何确定使用 Invoke-Expression 抛出的命令是否失败。甚至变量 $?、$LASTEXITCODE 或 -ErrorVariable 都对我没有帮助。

例如:

PS C:\> $cmd="cat c:\xxx.txt"

使用 Invoke-Expression 调用 $cmd

PS C:\> Invoke-Expression $cmd -ErrorVariable err

Get-Content : Cannot find path 'C:\xxx.txt' because it does not exist. At line:1 char:4 + cat <<<< c:\xxx.txt
+ CategoryInfo : ObjectNotFound: (C:\xxx.txt:String) [Get-Content], ItemNotFoundExcep
tion
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

$?是真的

PS C:\> $?

True

$LASTEXITCODE 是 0

PS C:\> $LASTEXITCODE

0

$err 是空的

PS C:\> $err

PS C:\>

我发现的唯一方法是在文件中重定向 STD_ERR 并测试该文件是否为空

PS C:\> Invoke-Expression $cmd 2>err.txt

PS C:\> cat err.txt

获取内容:找不到路径“C:\xxx.txt”,因为它不存在。在行:1 字符:4+ 猫 <<<< c:\xxx.txt + CategoryInfo : ObjectNotFound: (C:\xxx.txt:String) [Get-Content], ItemNotFoundExcep 化 + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

这是唯一且最好的方法吗?

最佳答案

试图将 STDERR 流捕获到变量工作时,我快疯了。我终于解决了。在 invoke-expression 命令中有一个怪癖,使整个 2&>1 重定向失败,但如果你省略 1 它会做正确的事情。

 function runDOScmd($cmd, $cmdargs)
{
# record the current ErrorActionPreference
$ep_restore = $ErrorActionPreference
# set the ErrorActionPreference
$ErrorActionPreference="SilentlyContinue"

# initialize the output vars
$errout = $stdout = ""

# After hours of tweak and run I stumbled on this solution
$null = iex "& $cmd $cmdargs 2>''" -ErrorVariable errout -OutVariable stdout
<# these are two apostrophes after the >
From what I can tell, in order to catch the stderr stream you need to try to redirect it,
the -ErrorVariable param won't get anything unless you do. It seems that powershell
intercepts the redirected stream, but it must be redirected first.
#>
# restore the ErrorActionPreference
$ErrorActionPreference=$ep_restore

# I do this because I am only interested in the message portion
# $errout is actually a full ErrorRecord object
$errrpt = ""
if($errout)
{
$errrpt = $errout[0].Exception
}

# return a 3 member arraylist with the results.
$LASTEXITCODE, $stdout, $errrpt
}

关于PowerShell:使用 Invoke-Expression 管理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com