PowerShell 使用New-Module命令动态创建对象 5


还记得当年怎样在PowerShell中动态创建对象吧?请猛戳这篇《堪称神曲的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.确认兵种(‘陆军’)
False
PS> $PLA | Get-Member


   TypeName: System.Management.Automation.PSCustomObject

Name        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 抗震救灾();
本文链接: https://www.pstips.net/new-object-by-new-module.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

5 条评论 “PowerShell 使用New-Module命令动态创建对象