正在从命令中获取错误代码,该命令通过管道传输到powershell中的"-replace"



我有一个powershell脚本,其中一个命令的输出通过管道传输到-replace,以确保不记录敏感信息。

$(mycommand do stuff) -replace 'START_SECRET.*?END_SECRET' 'SECRET_ELIDED'

然而,当mycommand失败时,错误会被-replace吃掉,并且脚本仍然在我希望它失败的地方成功。如何从该命令中获取错误代码?

我对看起来不太像这个-replace的解决方案持开放态度,但理想情况下,它应该是mycommand输出在生成时出现的,而不是像我保存输出、检查错误代码并稍后重新映射时那样一次出现。

您当前的示例也会在显示任何输出之前完成运行。如果你想在它到来时输出,你需要丢失$(...)。现在,每条线路都将在生成时沿管道向下发送

mycommand do stuff | ForEach-Object {$_ -replace 'START_SECRET.*?END_SECRET' 'SECRET_ELIDED' }

至于错误";被吃掉";,我没有看到这种行为,即使在$(...)中包装时也是如此

PS C:temp> $(dir nonexistentpath) -replace '^', '----'
Get-ChildItem: Cannot find path 'C:tempnonexistentpath' because it does not exist.

即使使用本机应用程序

PS C:Program FilesGIMP 2bin> $(.bzip2.exe sklfjslf)  -replace '^', '----'
bzip2.exe: Can't open input file sklfjslf: No such file or directory.

正如其他人所提到的,还不清楚您的命令是什么,甚至不清楚您对输出做了什么。如果您也在尝试捕获/处理错误记录,则需要使用2>&1将它们重定向到成功流

mycommand do stuff 2>&1 | ForEach-Object {$_ -replace 'START_SECRET.*?END_SECRET' 'SECRET_ELIDED' }

如果您正在运行的命令是cmdlet,您也可以使用-ErrorVariable来捕获错误记录,而不是将它们重定向到成功流。

PS C:temp> dir nonexistentpath -ErrorVariable errors
Get-ChildItem: Cannot find path 'C:tempnonexistentpath' because it does not exist.
PS C:temp> $errors
Get-ChildItem: Cannot find path 'C:tempnonexistentpath' because it does not exist.
$var = <#your stuff here#>
$var.Replace('START_SECRET.*?END_SECRET','SECRET_ELIDED')

最新更新