1

I need to create scirpt which add users from list (containing user Display name) to group Problem I encountered is : when I issue command :

PS C:\Users\pskwarek> foreach ($a in $csv) {(get-aduser -f "DisplayName -like 'Piotr Skwarek'").samaccountname}
pskwarek
pskwarek

but if I use $a variable it doesnt work :

PS C:\Users\pskwarek> foreach ($a in $csv) {(get-aduser -f "DisplayName -like '$a.name'").samaccountname}

next step I would like to pass it to :

Add-adgroupMember -identity "groupname" -member samaccountname

but I can't make that single step

edit

PS C:\Users\pskwarek> $csv
Name
----
Piotr Skwarek
Renata Skwarek
1
  • PS C:\Users\pskwarek> $csv Name ---- Piotr Skwarek Renata Skwarek Commented Mar 4, 2013 at 13:37

4 Answers 4

2

You need to put $a.name in a subexpression:

foreach ($a in $csv) 
{
    $user = Get-ADUser -Filter "DisplayName -like '$($a.name)'" 
    Add-ADGroupMember groupname -Members $user
}
Sign up to request clarification or add additional context in comments.

1 Comment

The syntax of that solution is actually clearer than mine, I always forget about this :p
0
foreach ($a in $csv) 
{
 $sb = [scriptblock]::create("DisplayName -like '*$a*'")
 (get-aduser -f $sb).SamAccountName
}

Comments

0

Try this:

foreach ($a in $csv) {(get-aduser -f ("DisplayName -like '{0}'" -f $a.name)).samaccountname}

You cannot use members of a variable directly in a string as you did. Using string formatting (the '-f' syntax I proposed) always works. Another solution would be to use a temporary variable to store $a.name

2 Comments

I am new to scripting and have to admit I don't get it altough it worked fine thx
Basically, in PS, you can construct strings and put "placeholders" for variables in them: $string = ("This is {0} {1}" -f "my","script") This just tells PowerShell to replace {0} by the first element of the list that's placed after '-s', and {1} by the second, and so on.
0

Try this:

$csv | % { Add-ADGroupMember -Identity "Groupname" -Member $_.Name  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.