Mysterious different conversion to string [] of seemingly identical input

While researching a problem, I found that the reason was an unexpected different conversion to the string [] that seemed to be the same input. Namely, in the code below, two commands return the same two elements, File1.txt and File2.txt. But converting to string [] gives different results, see Comments.

Any ideas why? It could be a mistake. If someone thinks so, I serve it. But it would be nice to understand what is happening and avoid traps.

# *** WARNING # *** Make sure you do not have anything in C:\TEMP\Test # *** The code creates C:\TEMP\Test with File1.txt, File2.txt # Make C:\TEMP\Test and two test files $null = mkdir C:\TEMP\Test -Force 1 | Set-Content C:\TEMP\Test\File1.txt 1 | Set-Content C:\TEMP\Test\File2.txt # This gets just file names [string[]](Get-ChildItem C:\TEMP\Test) # This gets full file paths [string[]](Get-ChildItem C:\TEMP\Test -Include *) # Output: # File1.txt # File2.txt # C:\TEMP\Test\File1.txt # C:\TEMP\Test\File2.txt 
+3
powershell
source share
1 answer

Well, I have some clues (maybe the question was stimulated by my thoughts). Yes, this is a kind of trap not only in PowerShell (but PowerShell allows).

Apparently, PowerShell uses ToString() to convert. And it was the wrong assumption that System.IO.FileInfo.ToString() returns FullName . The reflector shows that it returns base.OriginalPath , which is just what was passed in the constructor, not necessarily the full path.

Here is a demo:

 Set-Location C:\TEMP\Test [string](New-Object IO.FileInfo File1.txt) [string](New-Object IO.FileInfo C:\TEMP\Test\File1.txt) [string](New-Object IO.FileInfo ./..//Test///..Test\File1.txt) # Output: # File1.txt # C:\TEMP\Test\File1.txt # ./..//Test///..Test\File1.txt 

Thus, it seems that the first Get-ChildItem uses only names when creating FileInfo objects, and the second Get-ChildItem with the –Include parameter uses full paths. This is mistake? It looks controversial. This may be a feature, dubious, but still with some basic reasons. I doubt though ...

+8
source share

All Articles