在调查一些问题时,我发现原因是看似相同的输入数据对 string[] 的意外不同转换。即,在下面的代码中,两个命令都返回相同的两项 File1.txt 和 File2.txt。但是转换为 string[] 会给出不同的结果,请参阅注释。
有什么想法吗?这可能是一个错误。如果有人也这么认为,我会提交。但最好了解正在发生的事情并避免这样的陷阱。
# *** 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
好吧,我得到了一些线索(可能是发布问题激发了我的想法)。是的,这是一种陷阱,不仅在 PowerShell 中如此(但 PowerShell 使其成为可能)。
显然 PowerShell 只是使用ToString()
用于转换。这是一个错误的假设System.IO.FileInfo.ToString()
返回FullName
。 Reflector 显示它返回base.OriginalPath
这只是构造函数中传递的内容,不需要完整路径。
这是演示:
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
因此,它看起来像第一个Get-ChildItem
在创建时仅使用名称FileInfo
对象和第二个Get-ChildItem
与–Include
参数使用完整路径。这是一个错误吗?现在看来值得商榷。这可能是一个有问题的功能,但仍然有一些根本原因。但我怀疑……
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)