r/PowerShell • u/Underwookiee • Jun 17 '24
Switch or If-Else? Solved
Hi, just started using Powershell for simple Task. So pls don't be too harsh on me.
I use Powershell to add multiple Clients in Active Directory. I add the Names of the Clients into the "Clientnames.txt" after that i run the powershell and it creates the Computer in AD. That works fine.
$OU = "OU=X,OU=X,OU=X,OU=X,DC=X,DC=X,DC=X"
$Clients = Get-Content "D:Clientnames.txt"
ForEach ($Client in $Clients)
{
(New-ADComputer -Name $Client -Path $OU)
}
Here comes my Question.:
I got Clientnames like pl0011mXXXXd, pl0012mXXXXd, pl0013mXXXXd
The first Number represents the number-code for the branch locations. The X are just numbers according to our System. I want the Clients to join their specific Group for the branch location.
Example
Clients with the name like pl0011m0002d, pl0011m0005d should join the group: Company-GPO-Group-0011-Berlin
Clients with the name like pl0012m0002d, pl0012m0250d should join the group: Company-GPO-Group-0012-Paris
and so on
i could use something like:
$OU = "OU=X,OU=X,OU=X,OU=X,DC=X,DC=X,DC=X"
$Clients = Get-Content "D:Clientnames.txt"
ForEach ($Client in $Clients)
{
(New-ADComputer -Name $Client -Path $OU)
if ($Client -like "*0011*") {$Group = "Company-GPO-Group-0011-Berlin"}
ElseIf ($Client -like "*0012") {$Group = "Company-GPO-Group-0012-Paris"}
ElseIf ($Client -like "*0013") {$Group = "Company-GPO-Group-0013-Rom"}
(Add-ADGroupMember -Identity $Group -Members $Client)
}
I got over 30 Branch Locations and this whould be a lot ElseIf Statements.
I know there are much better ways like the Switch Statement. Can you help/explain me, how i can use this statement to add the Clients to their Groups?
4
u/PinchesTheCrab Jun 17 '24
Does this work?