我发现使用 powershell 时出现了一个奇怪的行为。
单独引用对象的输出不同于对同一对象调用的 ToString() 方法的输出。
调用的方法或属性是什么
Write-Output "$a"
这是我运行示例的目录
> PS C:\temp\testps> DIR
Directory: C:\temp\testps
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 03/12/2010 11.21 8 1.txt
-a--- 03/12/2010 11.21 8 2.txt
-a--- 03/12/2010 11.21 8 3.txt
这里我将文件集合分配给 $q 对象
PS C:\temp\testps> $q = Get-ChildItem . "*.txt"
现在我想打印文件名,但收到意外输出
PS C:\temp\testps> foreach ($a in $q) {Write-Output $a}
Directory: C:\temp\testps
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 03/12/2010 11.21 8 1.txt
-a--- 03/12/2010 11.21 8 2.txt
-a--- 03/12/2010 11.21 8 3.txt
在对象名称周围加上引号显示了正确的行为
PS C:\temp\testps> foreach ($a in $q) {Write-Output "$a"}
1.txt
2.txt
3.txt
这只是第一个对象的输出。它看起来像整个 DIR 命令输出,直到第一个文件名。未解析。
PS C:\temp\testps> foreach ($a in $q) {Write-Output $a;break}
Directory: C:\temp\testps
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 03/12/2010 11.21 8 1.txt
ToString() 方法的行为类似于引用的对象。
PS C:\temp\testps> foreach ($a in $q) {Write-Output $a.ToString()}
1.txt
2.txt
3.txt
最佳答案
第一种情况 Write-Output $a
,对象 (System.IO.FileInfo) 由 PowerShell 格式化引擎根据存储在 $pshome\FileSystem.format.ps1xml
中的格式数据进行格式化。 .也就是说,真正执行的是:
Write-Output $a | Out-Default
Out-Default 在管道的末尾隐式执行,它是根据格式化数据进行格式化的 cmdlet。
在
"$a"
案例,ToString()
代表被使用。
关于powershell - Powershell 中的 Write-Output 对对象调用的默认方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4346343/