在 Powershell 中打印对象属性 [英] Printing object properties in Powershell
问题描述
在交互式控制台中工作时,如果我定义一个新对象并为它分配一些属性值,如下所示:
When working in the interactive console if I define a new object and assign some property values to it like this:
$obj = New-Object System.String
$obj | Add-Member NoteProperty SomeProperty "Test"
然后,当我在交互式窗口中输入变量的名称时,Powershell 会为我提供对象属性和值的摘要:
Then when I type the name of my variable into the interactive window Powershell gives me a summary of the object properties and values:
PS C:\demo> $obj
SomeProperty
------------
Test
我基本上只想在脚本中的函数中执行此操作.该函数创建一个对象并设置一些属性值,我希望它在返回之前将对象值的摘要打印到 Powershell 窗口.我尝试在函数中使用 Write-Host:
I basically want to do just this but from within a function in a script. The function creates an object and sets some property values and I want it to print out a summary of the object values to the Powershell window before returning. I tried using Write-Host within the function:
Write-Host $obj
但这只是输出对象的类型而不是摘要:
But this just output the type of the object not the summary:
System.Object
如何让我的函数将对象属性值的摘要输出到 Powershell 窗口?
How can I have my function output a summary of the object's property values to the Powershell window?
推荐答案
试试这个:
Write-Host ($obj | Format-Table | Out-String)
或
Write-Host ($obj | Format-List | Out-String)
这篇关于在 Powershell 中打印对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!