powershell - Powershell PSCustomObject 提取值
问题描述
当创建和使用 PSCustomObjects 导致 NoteProperty 成员具有“定义”(如下所示)时,是否有任何简单的编程方法可以从定义字段中选择值而不诉诸拆分字符串?
例如下面,是否有一种“好”的方法可以从不需要传统字符串操作的名称“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
谢谢。
更新:按照 Thomas 的指导,我想出了这个函数来从 PSObject 中提取 Noteproperty 成员并返回一个带有字段名称和值的 Hashtable:
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
}
谢谢!
解决方案
您可以像访问任何其他对象一样访问自定义对象的成员:
$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
推荐阅读
- firebase - Firebase 托管 Webhook
- user-tracking - 可以在用户流工具中打开网络分析插件吗?
- sql - 在使用窗口函数时在子查询和游标块中调用 AVG 函数时查询永远不会完成
- php - Laravel 8 单元测试 - assertJson() 如何在控制器中捕获它
- c++ - ESP32 上的 Spotify Web api 连接被拒绝
- python - Visual Studio 代码:忽略 Python 示例中的前导“>>>”
- python - 为什么在使用 cmake 时编译 swig 二进制文件只会产生一个 `pyd` 文件,而手动命令也会产生一个 `py` 文件?
- angular - Angular / RxJS - 在应用程序初始化期间不要重复相同的 GET 请求
- vba - VBA Word 将特定单词中的文本复制到文档末尾
- angular - 升级到 Angular 11 后,材质选项卡组不会更改选项卡