[英]How to output a PS object as a custom formatted string
I have an object with a set of properties (depth: 1). 我有一个具有一组属性的对象(深度:1)。 How to output the object as a string in a format like this:
如何以如下格式将对象输出为字符串:
{property1_name:property1_value} {property2_name:property2_value} {property3_name...
(the above is a single line, but property values can of course have newlines/carriage returns etc) (以上是一行,但属性值当然可以有换行符/回车等)
Let's assume I do not know the property names, they can change. 我们假设我不知道属性名称,它们可以改变。
Thank you! 谢谢!
It'll actually depend on what object you're looking through. 它实际上取决于你正在寻找的对象。 I tested this out on a csv, and it works decently, although you may want to do some minor formatting for a different type of object.
我在csv上对此进行了测试,虽然您可能希望对不同类型的对象进行一些次要格式化,但它的工作正常。
$csv |
Get-Member |
Where-Object {$_.MemberType -eq "NoteProperty"} |
Select-Object -Property Name |
ForEach-Object {
"{" + $_.Name + " : " + $csv.($_.Name) + "}"
}
For example, depending on what you see when you do $csv | Get-Member
例如,取决于你在执行
$csv | Get-Member
时看到的内容 $csv | Get-Member
, you may want to change NoteProperty
to Property
or something else. $csv | Get-Member
,您可能想要将NoteProperty
更改为Property
或其他内容。 This should probably work though. 这应该可行。
Note that you also have to change the name of the variable (currently $csv
) in two places. 请注意,您还必须在两个位置更改变量的名称(当前
$csv
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.