2

I have the following script in Powershell ISE.

cd E:\Data
@"
xxxx.zip
yyyy.zip
"@ -split "`n" | % { echo "'$_'"; test-path -path "$_" -EA Stop }

However it always raises error.

'xxxx.ZIP'
False
Illegal characters in path.
At line:175 char:27
+ % { echo "'$_'"; test-path <<<<  -path "$_" -EA Stop }
    + CategoryInfo          : InvalidArgument: (E:\Data\xxxx.ZIP:String) [Test-Path], ArgumentException
    + FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.TestPathCommand

However, I can run Test-Path -path xxxx.zip or just hard code 'xxxx.zip' in the script and it runs fine. What's the problem of piped string?

Update

If I change the last script to % { echo "'$_'"; "test-path -path $_ -EA Stop" } and copy/paste the output ("test-path -path xxxx.ZIP -EA Stop") to the command line. It works.

Update

It seems it works in powershell console. An ISE bug?

4

3 回答 3

4

在 ISE 中,here-string 应使用回车符后跟 powershell new line进行拆分,如下所示:

cd E:\Data
@"
xxxx.zip
yyyy.zip
"@ -split "`r`n" | % { echo "'$_'"; test-path -path "$_" -EA Stop }

使用此功能时:

function asciiToHex($a)
{
$b = $a.ToCharArray();
Foreach ($element in $b) {$c = $c + "%#x" + [System.String]::Format("{0:X}",
[System.Convert]::ToUInt32($element)) + ";"}
$c
}

在我们得到的ise中转换here-string:

asciitohex $t
%#x78;%#x78;%#x78;%#x78;%#x2E;%#x7A;%#x69;%#x70;%#xD;%#xA;%#x79;%#x79;%#x79;%#x79;%#x2E;%#x7A;%#x69;%#x70;

但是在powershell控制台中我们得到

asciitohex $t
%#x78;%#x78;%#x78;%#x78;%#x2E;%#x7A;%#x69;%#x70;%#xA;%#x79;%#x79;%#x79;%#x79;%#x2E;%#x7A;%#x69;%#x70;
于 2012-01-06T21:43:11.893 回答
3

在 ISE 和控制台中使用正则表达式和-split.

cd C:\
@"
xxxx.zip
yyyy.zip
"@ -split "`r`n|`n" | % { echo "'$_'"; test-path -path "$_" -EA Stop }
于 2012-01-06T23:50:51.843 回答
2

您确定这正是您正在执行的脚本吗?我无法复制问题。

NTCs>  @"
>> xxxx.zip
>> yyyy.zip
>> "@ -split "`n"|%{echo "'$_'";test-path -path "$_" -ea stop}
>>
'xxxx.zip'
False
'yyyy.zip'
False

更新 要在 ISE 和控制台中工作,请将返回字符与问号(0 或 1 次)一起放置:

  @"
 xxxx.zip
 yyyy.zip
 "@ -split "`r?`n"|%{echo "'$_'";test-path -path "$_" -ea stop}
于 2012-01-06T20:42:51.690 回答