此脚本基于CSV创建OU,并将它们放入MyLab OU中,并创建2个子OU。它还检查CSV中的OU是否已经存在,然后输出它。我一直试图弄清楚如何为SubOU做到这一点,所以如果其中一个存在,另一个仍然是创建的。有人能为我指明正确的方向吗?
#Imports CSV file
$MyOUs = Import-csv C:\OUs.csv -Delimiter ","
#Sets parent path to main OU
$ParentPath = "OU=MyLab,DC=MyLab,DC=local"
#Perform actions for each OU in the CSV file
foreach ($OU in $MyOUs){
$Name = $OU.Name
#Check if an OU within the CSV file already exists
$Check = Get-ADOrganizationalUnit -filter * | Where-Object {$_.name -eq $OU.name} | select name
#If it does the text within the write-host is output
if ( $OU.name -eq $Check.name) {
write-host $OU.name "OU already exists"}
#if not the OU is created, with a 2 sub ous created within it
else{New-ADOrganizationalUnit -Name $Name -Path $ParentPath -ProtectedFromAccidentalDeletion $false
$SubOUs = "Department1", "Department2"
$subPath = "OU="+$OU.name+","+$ParentPath
foreach ($SubOU in $SubOUs){
New-ADOrganizationalUnit -Name $SubOU -Path $subPath -ProtectedFromAccidentalDeletion $false
}
}}
发布于 2022-09-15 20:04:05
要始终创建子of,可以在创建父of的if之外执行另一个if检查。这是我保持大多数事物不变的方法,但是改进了对OU的检查:
#Imports CSV file
$MyOUs = Import-csv C:\OUs.csv -Delimiter ","
#Query existing OUs only once at the start
$existingOUs = Get-ADOrganizationalUnit -filter *
#Sets parent path to main OU
$ParentPath = "OU=MyLab,DC=MyLab,DC=local"
#Perform actions for each OU in the CSV file
foreach ($OU in $MyOUs){
# Build distinguished name
$DN = "OU="+$OU.name+","+$ParentPath
#check for OU in existing list
if ($existingOUs.DistinguishedName -contains $DN) { write-host $OU.name "OU $DN already exists" }
else {
New-ADOrganizationalUnit -Name $Name -Path $ParentPath -ProtectedFromAccidentalDeletion $false
}
# then create 2 sub OUs within each $OU
$SubOUs = "Department1", "Department2"
foreach ($SubOU in $SubOUs){
$SubDN = "OU="+$SubOU.name+","+$DN
# check if sub OU exists
if ($existingOUs.DistinguishedName -contains $SubDN) { write-host $OU.name "OU $DN already exists" }
else {
New-ADOrganizationalUnit -Name $SubOU -Path $DN -ProtectedFromAccidentalDeletion $false
}
}
}https://stackoverflow.com/questions/73735000
复制相似问题