3

so there's a lot of similar topics to this I've found, but I can't find anything that correlates with my issue.

invoke-command -computername $serverLocation -Credential $cred -filepath "C:\path\script2.ps1" -ArgumentList $configPath

I am calling a for a script that is stored on my local machine to run on another server. Everything works as intended except for passing the "configPath" variable. This is how I initiate the script -

. .\script1.ps1 -serverLocation 'serverNameHere' -username 'userNameHere' -configPath 'configPathHere' 

It correctly grabs all the other parameters I pass into the first script. It just won't pass the configPath to the second script in the 'filepath'.

How can I get this parameter to pass through? Thanks so much.

crystallinity
  • 431
  • 2
  • 6
  • 10

1 Answers1

1

In script2.ps1, you should define a param() block that accepts the parameter, and then you can refer to it by whatever name you give it. If you don't want to use a param() block then using $args[0] should work.

briantist
  • 45,546
  • 6
  • 82
  • 127
  • Yes, I control/created all the scripts in this process. I'm confused as to why you have it listed in the 3rd position? I am only passing one argument to the script that is being initiated on the remote server, so wouldn't it just be -ArgumentList $configPath? I understand what you mean by it doesn't know names - how do I call it in my other script then? args[0] or something? Also, do I need to list it in the param () list in the script that calls it? Thanks again. – crystallinity May 26 '16 at 16:05
  • I have it in the third position because your example invocation shows it in the third position, but its actual position will be based on where it's defined in the called script's param block (it could also be defined with a specific position to override the regular order). – briantist May 26 '16 at 16:11
  • Oh I think I see what's happening now. `script1.ps1` contains the `Invoke-Command` invocation, and `script2.ps1` is a different script. In that case, in `script2.ps1`, you should define a `param()` block that accepts the parameter, and then you can refer to it by whatever name you give it. If you don't want to use a `param()` block then using `$args` should work. – briantist May 26 '16 at 16:13
  • Hey, I was playing with it before you responded based on your initial answer. So I did -ArgumentList $configPath, then went to my second script and put $configPath in the first line at the top of my parameter block. It passed through :) Thanks so much for your help and your prompt responses!! – crystallinity May 26 '16 at 16:14
  • 1
    @crystallinity cool, I replaced the answer with the comment that more accurately reflects the problem. – briantist May 26 '16 at 16:16
  • The $using:var scope might work too for a variable outside the script. – js2010 Mar 30 '20 at 15:00