在PowerShell中加载延迟?

时间:2015-11-17 07:34:17

标签: performance powershell lazy-loading

我们可以推迟变量初始化,直到需要它吗?

我想要做的是预定义我的个人资料中包含AD计算机列表的一些变量:

让我说我想要:

$ OU1_workstation 将填充在OU =工作站中找到的计算机,OU = OU1,dc = domain,dc = com

$ OU2_workstation 填写了在中找到的计算机 OU =工作站,OU = OU2,dc =域,dc = com等等......

我使用以下脚本来执行此操作,但计算需要30秒,所以目前我无法将其放入我的个人资料中...

Get-ADOrganizationalUnit -SearchScope onelevel -Filter "*" -Properties "name","distinguishedname" |%{
    set-Variable -Name "$($_.name)_workstation" -value (Get-ADComputer -Searchbase "OU=workstations,$($_.Distinguishedname)" -Filter * )
}    

powershell提供哪些选项?

1 个答案:

答案 0 :(得分:0)

最后,根据前一个问题的@Richard's reply,我选择了以下路径来实现某种延迟加载:使用scriptproperty的{​​{1}}。 所以我可以把它放在我的个人资料中

PSCustomObject

然后在需要时我可以致电#requires -module activedirectory $server=New-Object PSCustomObject Get-ADOrganizationalUnit -SearchScope onelevel -Filter "*" -Properties "name","distinguishedname" | ?{ $_.name -notmatch 'Administrateurs|Administration|Comptes de deploiement|Contacts|Domain Controllers|Groupes|Serveurs|Services' } | %{ $OU=$_.name $s=[scriptblock]::Create("Get-ADComputer -SearchBase ""OU=servers,OU=$OU,DC=domain,DC=com"" -Filter 'name -notlike "" *old""' |select -expand name") $server| Add-Member -MemberType ScriptProperty -name $OU -value $s -Force } 以获取此OU下的所有服务器,$server.OU1等...