2014-02-24 36 views
1

首先,这里是我的代码:ErrorVariable输出并不如预期

$InputPath = "\\Really\long\path\etc" 
Get-ChildItem -Path $InputPath -Recurse -Force -ErrorVariable ErrorPath 
$ErrorPath | select TargetObject 

我面临的问题是与ErrorVariable参数。 Get-ChildItem要处理的路径太长(通常大约250个字符)。当我管$ ErrorPath选择,输出看起来是这样的:

TargetObject : \\Really\long\path\etc\1 

TargetObject : \\Really\long\path\etc\2 

TargetObject : \\Really\long\path\etc\3 

但是,如果我跑最后一行再次(可以通过运行选择或通过手动键入它),则输出变为这样:

TargetObject 
------------ 
\\Really\long\path\etc\1 
\\Really\long\path\etc\2 
\\Really\long\path\etc\3 

我不知道该如何解释。我更喜欢第二个输出,但我不知道为什么它从第一次到第二次不同。有任何想法吗?

回答

2

当有多个类型的对象在一管道中的第一对象类型确定用于其余对象的格式。如果您在命令提示符下单独运行命令,则不会看到这一点。每一行开始一个新的管道。但是,当您在脚本中运行这些命令时,整个脚本将作为管线执行。要解决此问题,请使用Out-Default例如:

$InputPath = "\\Really\long\path\etc" 
Get-ChildItem $InputPath -Recurse -Force -ErrorVariable ErrorPath 
$ErrorPath | select TargetObject | Out-Default 
0

前一个输出是列表格式,后者是表格格式。可以强制一个或另一个通过分别管道数据到Format-ListFormat-Table的cmdlet:

PS C:\>$ErrorPath | select TargetObject | Format-List 


TargetObject : \\Really\long\path\etc\1 

TargetObject : \\Really\long\path\etc\2 

TargetObject : \\Really\long\path\etc\3 


PS C:\>$ErrorPath | select TargetObject | Format-Table 

TargetObject 
------------ 
\\Really\long\path\etc\1 
\\Really\long\path\etc\2 
\\Really\long\path\etc\3
+0

但为什么会发生变化?当我执行两次相同的命令时,它不应该总是这样吗? –