I am in the process of trying to clean up some scripts we have and ran into an interesting issue. If I use the following to load a remote module (in this case ActiveDirectory):

$cred= Get-Credential
$session= New-PSSession -ComputerName dc1 -Credential $cred
Invoke-Command -ScriptBlock {Import-Module ActiveDirectory} -Session $session
Import-PSSession -Session $session -module ActiveDirectory -Prefix Rem

Creating a new user account using New-RemADUser -samaccountname $samname -etc everything works as expected.

However if I try to put it into a function, while there are no errors, no new account is created.


function newuser{
New-RemADUser -GivenName $givenname -SurName...
$gname= Read-Host "Given name"

So my question is can the function not view the New-RemADUser cmdlet despite it running in the same script scope? Would I have to use Invoke-Command -Session $session New-ADUser... in order for the function to work? Or is there some best practice or obvious reason my initial way to try it wouldn't work (values don't pass correctly, remote command doesn't 'exist' within the function, etc..)?


When you call a PowerShell function, the parameters are not comma-separated like in C#. When you call your function like this:


the parser treats ($a,$b,$c) as one single parameter, and since newuser expects the first argument to be a string, the parser tries to convert it to a single string - it's the equivalent of calling:

newuser -GivenName "$a $b $c"

Try calling it with a space separating the arguments instead, or, if you wanna be absolutely sure, give the parameter names explicitly:

newuser -GivenName $gname -Surname $surname -SamAccountName $etc
  • The spaces helped but having the parentheticals was what was keeping all the arguments seen as one string. This is a rather confusing way to call a function and the built in about_Functions only explained the syntax for calling the function using the pipeline to supply or explicitly calling the switch to be used. Still it put me on the right track to see what to look for so thank you. – David V Apr 26 '15 at 12:12
  • @DavidV Glad I could help, sorry if it was poorly worded. You might also benefit from looking at the about_Parsing help file, explaining how the parser behavior differs when looking at arguments as opposed to expression – Mathias R. Jessen Apr 26 '15 at 12:16
  • Will do thanks. The wording wasn't poor more just me expecting the arguments to be wrapped in something, guess I'm just not as familiar with the syntax as I thought. – David V Apr 26 '15 at 12:32
  • No shame in that, just keep on reading, coding and learning :-) Unless you're calling a native .NET method, parentheses usually only mean one thing in PowerShell: evaluation precedence – Mathias R. Jessen Apr 26 '15 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.