1

I am working on a script that must change users in the middle of running in order to be able to access a network folder. I have figured out how to get the credentials working, but now cannot understand how to pass parameters to the second script that is being called. The code that I currently have:

$myJob = Start-Job -ScriptBlock {& "\\my\folder\path\script.ps1" -serverName $serverName -serverInstance $serverInstance} -Credential $cred
        $myJob | Wait-Job
        $myJob | Receive-Job -Keep

I need to pass the serverName and serverInstance variables to the script that Start-Job is running, while also still being able to use credential. Is there a way to do this?

I have investigated Invoke-Command and Invoke-Expression, but neither of those fit this situation. Invoke-Command doesn't work with remote computers/drives and Invoke-Expression doesn't work with credentials. I tried the answer that was provided here, but that would not correctly pass in the parameters either.

Any help is much appreciated as I have been working on this problem for a few hours now. I am sure I am missing something obvious.

3
  • 1
    You can use the using keyword here: -serverName $using:serverName -serverInstance $using:serverinstance. Commented Jun 4, 2019 at 21:27
  • 1
    or Start-Job -ArgumentList $var1,$var2 -ScriptBlock {$args[0],$args[1]} Commented Jun 4, 2019 at 21:31
  • @AdminOfThings Awesome thank you! That worked perfectly. I have never come across $using so I have something new to research and learn about. Commented Jun 4, 2019 at 21:40

1 Answer 1

2

You can use the using scope modifier provided you are on PowerShell version 3 or higher:

$myJob = Start-Job -ScriptBlock {& "\\my\folder\path\script.ps1" -serverName $using:serverName -serverInstance $using:serverInstance}

You can also use local variables in remote commands, but you must indicate that the variable is defined in the local session. Beginning in Windows PowerShell 3.0, you can use the Using scope modifier to identify a local variable in a remote command. The syntax of Using is as follows: $Using:<VariableName>

If you are on PowerShell version 2, you will need to utilize the -ArgumentList parameter and then modify your scriptblock to accept the arguments that are passed. Avshalom comments on one way to do this.

See About_Remote_Variables for more information.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.