還記得當(dāng)年怎樣在PowerShell中動態(tài)創(chuàng)建對象吧?今天要分享的方法不敢自詡高大上,但也足以讓New-Object感到汗顏。
背景
在System Center Operation Manager中有個Management Pack,叫做:“Microsoft.SystemCenter.OperationsManager.SummaryDashboard”。在該MP中有個Discovery叫做:“Collect agent configurations”。該工作流中用到了一段腳本,其中使用了New-Module命令。
New-Module就是在內(nèi)存中動態(tài)生成一個Module組件。用它來自定義對象有點大材小用了。
演習(xí)
$PLA = New-Module { $名稱 = ‘中國人民解放軍' $軍區(qū) = @('沈陽軍區(qū)','北京軍區(qū)','濟南軍區(qū)','南京軍區(qū)','廣州軍區(qū)','成都軍區(qū)','蘭州軍區(qū)') $兵種 = @('海軍','空軍','第二炮兵') function 保衛(wèi)黨 { return $true } function 保衛(wèi)人民 { return $null } function 抗洪搶險 { return $true } function 抗震救災(zāi) { return $true } function 確認(rèn)兵種 { param($某兵種) if ($this.兵種.Contains($某兵種)){ return $true } return $false } Export-ModuleMember -Variable * -Function * } -AsCustomObject
PS> $PLA兵種 軍區(qū) 名稱 -- -- -- {海軍, 空軍, 第二炮兵} {沈陽軍區(qū), 北京軍區(qū), 濟南軍區(qū), 南京軍區(qū)...} 中國人民解放軍 PS> $PLA.確認(rèn)兵種(‘陸軍')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[]軍區(qū) NoteProperty System.Object[] 軍區(qū)=System.Object[]名稱 NoteProperty System.String 名稱=中國人民解放軍 保衛(wèi)人民 ScriptMethod System.Object 保衛(wèi)人民(); 保衛(wèi)黨 ScriptMethod System.Object 保衛(wèi)黨(); 抗洪搶險 ScriptMethod System.Object 抗洪搶險(); 抗震救災(zāi) ScriptMethod System.Object 抗震救災(zāi)();
新聞熱點
疑難解答
圖片精選