Powershell ISE "Illegal characters in path" when piping paths to test-path?

5.2k Views Asked by At

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?

3

There are 3 best solutions below

3
On BEST ANSWER

In the ISE the here-string should be split using a carriage return followed by a powershell new line, like this:

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

When using this function:

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

to convert the here-string in the ise we get:

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

however in the powershell console we get

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

Are you sure that this is exactly the script that you are executing? I can't replicate the problem.

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

Updated To work in ISE and console put the return character with a question sign (0 or 1 ocurrence):

  @"
 xxxx.zip
 yyyy.zip
 "@ -split "`r?`n"|%{echo "'$_'";test-path -path "$_" -ea stop}
0
On

An example to work in both the ISE and the console using a regular expression with -split.

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