还记得当年怎样在PowerShell中动态创建对象吧?今天要分享的方法不敢自诩高大上,但也足以让New-Object感到汗颜。
背景
在System Center Operation Manager中有个Management Pack,叫做:“Microsoft.SystemCenter.OperationsManager.SummaryDashboard”。在该MP中有个Discovery叫做:“Collect agent configurations”。该工作流中用到了一段脚本,其中使用了New-Module命令。
New-Module就是在内存中动态生成一个Module组件。用它来自定义对象有点大材小用了。
演习
$PLA = New-Module { $名称 = ‘中国人民解放军" $军区 = @("沈阳军区","北京军区","济南军区","南京军区","广州军区","成都军区","兰州军区") $兵种 = @("海军","空军","第二炮兵")function 保卫党 {return $true }function 保卫人民 { return $null }function 抗洪抢险 { return $true }function 抗震救灾 { return $true }function 确认兵种 { param($某兵种) if ($this.兵种.Contains($某兵种)){return $true} return $false } Export-ModuleMember -Variable * -Function * } -AsCustomObject
PS> $PLA兵种军区 名称 ---- -- {海军, 空军, 第二炮兵}{沈阳军区, 北京军区, 济南军区, 南京军区...} 中国人民解放军PS> $PLA.确认兵种(‘陆军")FalsePS> $PLA | Get-MemberTypeName: System.Management.Automation.PSCustomObjectNameMemberTypeDefinition------------------------Equals Methodbool Equals(System.Object obj)GetHashCode Methodint GetHashCode() GetType Methodtype GetType()ToStringMethodstring ToString() 兵种 NoteProperty System.Object[] 兵种=System.Object[]军区 NoteProperty System.Object[] 军区=System.Object[]名称 NoteProperty System.String 名称=中国人民解放军 保卫人民ScriptMethod System.Object 保卫人民(); 保卫党 ScriptMethod System.Object 保卫党(); 抗洪抢险ScriptMethod System.Object 抗洪抢险(); 抗震救灾ScriptMethod System.Object 抗震救灾();