当创建和使用PSCustomObjects时,会产生一个带有' definition‘的NoteProperty成员(如下所示),有没有什么简单的、编程的方法来从definition字段中选择值,而不需要拆分字符串?
例如,有没有一种“好”的方法来从name 'token‘的字段中提取值'silver’,而不需要传统的字符串操作?我一直在尝试使用select和-ExpandProperty,但是速度很快,如果能在正确的方向上推动一下,我会很感激。
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
bsw NoteProperty decimal bsw=3.14
name NoteProperty string name=chris
token NoteProperty string token=silver
volume NoteProperty decimal volume=17.22谢谢。
更新:遵循托马斯的指导,我想出了这个函数来从PSObject中提取Noteproperty成员,并返回一个包含字段名称和值的哈希表:
function convertObjectToHash($psObj) {
$hashBack = @{}
try {
$psObjFieldNames = $psObj | get-member -type NoteProperty | select "Name"
$psObjFieldNames | foreach-object {
$hashBack.Add($_.Name,$psObj.$($_.Name)) }
}catch{ "Error: $_" }
return $hashBack
}谢谢!
发布于 2020-05-10 19:19:27
您可以像在任何其他对象中一样访问自定义对象的成员:
$myCustomObject.token复制:
$myCustomObject = New-Object -TypeName psobject
$myCustomObject | Add-Member -MemberType NoteProperty -Name bsw -Value 3.14
$myCustomObject | Add-Member -MemberType NoteProperty -Name name -Value "chris"
$myCustomObject | Add-Member -MemberType NoteProperty -Name token -Value "silver"
$myCustomObject | Add-Member -MemberType NoteProperty -Name volume -Value 17.22
$myCustomObject | Get-Member -MemberType NoteProperty
$myCustomObject.token输出:
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
bsw NoteProperty System.Double bsw=3.14
name NoteProperty string name=chris
token NoteProperty string token=silver
volume NoteProperty System.Double volume=17.22
silver发布于 2020-05-10 19:23:50
由于您在对象中存储了字符串值,因此我认为没有其他方法可以只提取值silver,然后使用string方法只获取等号后面的部分。
($obj.token -split '=', 2)[-1] --> silver为什么不使用一个名为value的额外属性创建自定义对象,并添加从Definition属性中获取的值?喜欢
$obj = [PsCustomObject]@{'token' = 'string token=silver'; 'value' = 'silver'}https://stackoverflow.com/questions/61710841
复制相似问题