Lazy loading in powershell?

会有一股神秘感。 提交于 2019-12-13 04:39:01

问题


Can we defer a variable initialization untill it is needed ?

What I would like to do is predefine some variables in my profile that will contain a list of AD computer:

let's say I want:

$OU1_workstation to be fill with computers found in OU=workstations,OU=OU1,dc=domain,dc=com

$OU2_workstation fill with computers found in
OU=workstations,OU=OU2,dc=domain,dc=com and so on...

I use the following script to do it but it takes 30sec to compute, so currently I can't put that in my profile...

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

What options are available in powershell ?


回答1:


Finally, based on @Richard's reply of a previous question of mine, I've chosen the following path to achieve some sort of lazy loading : using a scriptproperty of a PSCustomObject. So I can put this in my profile

#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
}

then when needed I can call $server.OU1 to get all server under this OU, $server.OU2 etc...



来源:https://stackoverflow.com/questions/33751430/lazy-loading-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!