I have a CSV file which has a list of users and groups they belong to. I am trying to script the same to automate it using PowerShell but seem to be facing an error. When I try to debug it I see that for some reason the user name value is being blank.
Any assistance will be helpful.
$Users = import-csv -Path "C:\Scripts\listofusers.csv"
foreach-Object ($User in $Users)
{
$SAM = $User.'SAM'
$group = $User.'Group'
Add-ADGroupMember -Identity $group -Members "$SAM"
}
Test Data
Group SAM
IT Test1
Engineering Test3
Change:
foreach-Object ($User in $Users)
to:
foreach ($User in $Users)
The foreach
statement iterates over a collection of objects whereas the foreach-object
is used in a pipeline
Hence try the following:
$Users = import-csv -Path "C:\Scripts\listofusers.csv"
foreach ($User in $Users) {
$SAM = $User.'SAM'
$group = $User.'Group'
Add-ADGroupMember -Identity $group -Members "$SAM"
}
If data is as you wrote, then you need to define delimiter while importing data from CSV. By default, delimiter is comma, so its not fitting your data. Just use
$Users = import-csv -Path 'C:\Scripts\listofusers.csv' -Delimiter ' '
If that is not a space, but tab, then use `t (that's backtick in front of t).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.