PowerShell小技巧之使用New-Module命令动态创建对象
还记得当年怎样在PowerShell中动态创建对象吧?今天要分享的方法不敢自诩高大上,但也足以让New-Object感到汗颜。
背景
在SystemCenterOperationManager中有个ManagementPack,叫做:“Microsoft.SystemCenter.OperationsManager.SummaryDashboard”。在该MP中有个Discovery叫做:“Collectagentconfigurations”。该工作流中用到了一段脚本,其中使用了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.确认兵种(‘陆军') False PS>$PLA|Get-Member TypeName:System.Management.Automation.PSCustomObject NameMemberTypeDefinition ------------------------ EqualsMethodboolEquals(System.Objectobj) GetHashCodeMethodintGetHashCode() GetTypeMethodtypeGetType() ToStringMethodstringToString() 兵种NotePropertySystem.Object[]兵种=System.Object[] 军区NotePropertySystem.Object[]军区=System.Object[] 名称NotePropertySystem.String名称=中国人民解放军 保卫人民ScriptMethodSystem.Object保卫人民(); 保卫党ScriptMethodSystem.Object保卫党(); 抗洪抢险ScriptMethodSystem.Object抗洪抢险(); 抗震救灾ScriptMethodSystem.Object抗震救灾();