2

I am totally new with PowerShell and it might be a silly question

I have created a small script to add admin rights remotely:

$computername = Read-Host 'Computername';
$name = Read-Host 'UserName'; 
Enter-Pssession -computername $computername; 
Add-LocalGroupMember -Group "Administrators" -Member $name;

If I try to run it all together it doesn't work

but if I try to run it separately, it works

 $computername = Read-Host 'Computername'
 Enter-Pssession -computername $computername;

then

 $name = Read-Host 'UserName';
 Add-LocalGroupMember -Group "Administrators" -Member $name;

Would you mind telling me what is wrong?

Thank you!

2
  • You notice how the order of commands change when you run it seperatly? This is the reason it doesn't work. You don't parse the Username to the Session in the script. Commented Jul 5, 2018 at 7:20
  • Now it is clear, thank you for your help! Commented Jul 5, 2018 at 8:42

2 Answers 2

3

After you enter the PSSession in the script, the variable $name is set to $0 again, since you dont pass the variable through to the session.

I would try running the script like this:

$computername = Read-Host 'Computername'
$name = Read-Host 'UserName'

Invoke-Command {
  param($name)
  Add-LocalGroupMember -Group "Administrators" -Member $name
} -computer $computername -ArgumentList $name
Sign up to request clarification or add additional context in comments.

2 Comments

I just tried it with a user and it works perfectly, I understood where I was wrong, thank you for your help
@Cloudgr Glad I could help :). If the answer was correct and helped you, please mark it as correct (clicking the green check mark).
1

This is basically the same as Paxz answer but as a one-liner.

you can use local variables in the script block of Invoke-Command by prepending "using:".

$computername = Read-Host 'Computername'
$name = Read-Host 'UserName'

Invoke-Command -ComputerName $computername -ScriptBlock {Add-LocalGroupMember -Group "Administrators" -Member $using:name}

1 Comment

Thanks for the add up. TIL $using: was a thing.. :'D You may wanna include this as a ref in the answer: learn.microsoft.com/en-us/powershell/module/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.