Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 捕获调用表达式输出和重定向stderr时发生异常_Powershell - Fatal编程技术网

Powershell 捕获调用表达式输出和重定向stderr时发生异常

Powershell 捕获调用表达式输出和重定向stderr时发生异常,powershell,Powershell,我想捕获并记录调用表达式调用的所有输出(重定向stderr),但这样做,通常抛出的任何异常似乎都被吞没了 假设c:\temp\test已存在,此命令将引发异常: PS U:\> $cmd = "mkdir c:\temp\test" PS U:\> $output = Invoke-Expression $cmd New-Item : Item with specified name C:\temp\test already exists. At line:38 char:24 +

我想捕获并记录调用表达式调用的所有输出(重定向stderr),但这样做,通常抛出的任何异常似乎都被吞没了

假设c:\temp\test已存在,此命令将引发异常:

PS U:\> $cmd = "mkdir c:\temp\test"
PS U:\> $output = Invoke-Expression $cmd
New-Item : Item with specified name C:\temp\test already exists.
At line:38 char:24
+         $scriptCmd = {& <<<<  $wrappedCmd -Type Directory @PSBoundParameters }
    + CategoryInfo          : ResourceExists: (C:\temp\test:String) [New-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
这是一个简化的示例,我在函数中使用Invoke表达式进行多种类型的调用,并记录输出。因此,这不仅仅是让这个电话起作用的问题

此外,不捕获输出也会正确引发异常:

PS U:\> $cmd = "mkdir c:\temp\test 2>&1"
PS U:\> Invoke-Expression $cmd
New-Item : Item with specified name C:\temp\test already exists.
At line:38 char:24
+         $scriptCmd = {& <<<<  $wrappedCmd -Type Directory @PSBoundParameters }
    + CategoryInfo          : ResourceExists: (C:\temp\test:String) [New-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
PS U:\>$cmd=“mkdir c:\temp\test 2>&1”
PS U:\>调用表达式$cmd
新项:具有指定名称C:\temp\test的项已存在。
第38行字符:24

+$scriptCmd={&
$Error
是一个缓冲错误的数组。最近的错误存储在
$Error[0]
中。您可以将其与
$LASTEXITCODE
$?
结合使用

对于您的情况,我认为
-ErrorVariable
更合适。它是一个常用变量。有关详细信息,请参阅
获取有关\u commonparameters的帮助。语法为
-ErrorVariable[+]
。例如,以下命令创建
$e
变量,然后将
调用表达式中的任何错误存储在其中:

Invoke-Expression $cmd -ErrorVariable e
请注意,
$e
可能包含多个错误

因此,要回答您关于如何捕获所有输出并仍然显示错误的问题,请执行以下操作:

$output = Invoke-Expression $cmd -ErrorVariable e

抱歉,这不起作用。$e在运行此$output=iex“mkdir c:\temp\test 2>&1”时为空-ErrorVariable e$?在命令运行后为true,但$LASTEXITCODE至少显示了一些内容。
$e
为空,因为您正在将
STDERR
重定向到
STDOUT
!重定向STDERR是我问题的核心部分,您的回答指出使用ErrorVariable也会让我出错作为捕获所有输出。使用
$output=iex"mkdir c:\temp\test-ErrorVariable e
STDOUT
$output
中被捕获,
STDERR
$e
中被捕获,同时抛出异常。我认为这是您最初的问题。如果您还想将错误重定向到
$output
,请在inv之后执行
$output+=$e
相关的
$output = Invoke-Expression $cmd -ErrorVariable e