I am trying to write a script that I can run on a scheduled task to scan the computer accounts under a OU then use the computer account names that are found to create AD security groups in another OU that I will then use to apply administrative rights to each individual server.
I am having a little trouble getting the ForEach loop to work the way I want it.
Any help would be great.
Here is what I have so far.
$ServerAccounts = (Get-ADComputer -filter * -Properties name -SearchBase “OU=Servers,DC=Child,DC=Domain,DC=com” | FT Name)
ForEach ($i in $ServerAccounts) {New-ADGroup -Name “$i - LADM” -GroupScope Global -GroupCategory Security -Path ‘OU=Server Local Admin Computers,OU=Groups,DC=Child,DC=Domain,DC=com’}
$ServerAccounts = (Get-ADComputer -filter * -Properties name -SearchBase “OU=Servers,DC=Child,DC=Domain,DC=com” | (b)FT Name(/b)
ForEach ($i in $ServerAccounts) {New-ADGroup -Name “$i – LADM” -GroupScope Global -GroupCategory Security -Path ‘OU=Server Local Admin Computers,OU=Groups,DC=Child,DC=Domain,DC=com’}
Because you’re piping into Format-Table, you don’t actually have PowerShell objects anymore. $ServerAccounts in your example actually stores raw output data.
So try the command again, like this:
(pre)$ServerAccounts = (Get-ADComputer -filter * -Properties name -SearchBase “OU=Servers,DC=Child,DC=Domain,DC=com”
ForEach ($i in $ServerAccounts) {New-ADGroup -Name “$($i.Name) – LADM” -GroupScope Global -GroupCategory Security -Path ‘OU=Server Local Admin Computers,OU=Groups,DC=Child,DC=Domain,DC=com’}(/pre)
I don’t know the exact problem, but I suspect that some of the information below will likely be useful. In relation to number one below, you should probably read the eBook, The Big Book of PowerShell Gotchas, or at least the first chapter (click Resources > Free eBooks above).
Remove your Format-* cmdlet (FT). Replace it with Select-Object.
Name is a default property; it is returned without the need for the -Properties parameter.
Expand the Name property. This will return only the Name and not the table-like heading. You can do this by piping to Select-Object -ExpandProperty in any version of PowerShell, or using dotted-notation in PowerShell 3.0 and greater.
I don't know the exact problem, but I suspect that some of the information below will likely be useful. In relation to number one below, you should probably read the eBook, The Big Book of PowerShell Gotchas, or at least the first chapter (click Resources > Free eBooks above).
Remove your Format-* cmdlet (FT). Replace it with Select-Object.
Name is a default property; it is returned without the need for the -Properties parameter.
Expand the Name property. This will return only the Name and not the table-like heading. You can do this by piping to Select-Object -ExpandProperty in any version of PowerShell, or using dotted-notation in PowerShell 3.0 and greater.