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?

ca9163d9
  • 27,283
  • 64
  • 210
  • 413

3 Answers3

4

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;
jon Z
  • 15,838
  • 1
  • 33
  • 35
3

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 }
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
2

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}
mjsr
  • 7,410
  • 18
  • 57
  • 83
  • I am running these using Powershell ISE. Did you try it in ISE? – ca9163d9 Jan 06 '12 at 20:51
  • you are right, it happend only in ISE. It must be because the editor put that invicible character at the end of every line. Thank god the console don't do the same, ;D – mjsr Jan 06 '12 at 23:10