powershell - Powershell 中的 Write-Output 对对象调用的默认方法是什么?

标签 powershell

我发现使用 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/

相关文章:

c# - 使用 C# 设置 CertificatePolicy=$TrustAll

windows - 如何以与 "cmd/c <command>".execute() 相同的方式从 groovy 运行 PowerShell 命令?

powershell挂载DiskImage "The system cannot find the path specified."

json - 如何将对象参数作为哈希表传递到 json arm 模板中?

powershell - 如何开始使用 PowerShell?

regex - 使用 powershell 捕获数组中的正则表达式匹配

powershell - 将密码传递到-credential

powershell - 从 Powershell 并行 Foreach 循环返回值

powershell - 使用 WMI 远程扩展分区

powershell - 有没有办法捕获 ctrl-c 并要求用户确认?