還記得當年怎樣在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-Member TypeName: System.Management.Automation.PSCustomObjectName MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string 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 抗震救災();
新聞熱點
疑難解答
圖片精選