首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >powershell: 判断PSObject中是否有指定property的靠谱方法

powershell: 判断PSObject中是否有指定property的靠谱方法

作者头像
10km
发布2018-01-03 12:05:58
发布2018-01-03 12:05:58
1.9K0
举报
文章被收录于专栏:10km的专栏10km的专栏

如何判断一个PSObject中是否定义指定名称的属性,下面的代码中举出了三个方法

代码语言:javascript
复制
$test=New-Object PSObject -Property @{
    compiler=$null
    }
#方法一(不完全靠谱)    
$test.compiler -ne $null
#方法二
(Get-Member -inputobject $test -name "compiler" ) -ne $null
#方法三
($test.PSobject.Properties.name -match "compiler")

上面三个方法, 方法一虽然最简单却不完全靠谱,因为如果compiler是$null时,返回结果是错的。 靠谱的办法是二和三, 而方法三要求powerShell 3.0以上的版本才有效

参考:

https://stackoverflow.com/questions/26997511/how-can-you-test-if-an-object-has-a-specific-property

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年06月29日,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档