Mysterious different conversion to string[] of seemingly same input data

前端 未结 1 1129
失恋的感觉
失恋的感觉 2021-01-14 18:20

During investigation of some problem I found that the reason was unexpected different conversion to string[] of seemingly same input data. Namely, in the code below two comm

相关标签:
1条回答
  • 2021-01-14 18:47

    Well, I have got some clues (probably posting the question stimulated my thoughts). Yes, this is kind of a trap, not only in PowerShell (but PowerShell makes it possible).

    Apparently PowerShell just uses ToString() for conversion. And it was a wrong assumption that System.IO.FileInfo.ToString() returns the FullName. Reflector shows that it returns the base.OriginalPath which is just what was passed in the constructor, not necessary a full path.

    Here is the 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 looks like the first Get-ChildItem uses just names on creation of FileInfo objects and the second Get-ChildItem with the –Include parameter uses full paths. Is this a bug? It looks debatable now. It might be a feature, questionable, but still with some underlying reasons. I doubt, though…

    0 讨论(0)
提交回复
热议问题