1

I'm working on automating patches for a vendor app. I wanted to use powershell to iterate over a list of servers and use remoting to install on each box. However, one aspect is giving me a big headache. I have to call a cmd script provided by the vendor to set system variables prior to executing the installation script. So I call the script like so in powershell:

Invoke-Command -session $session {cmd /k ($args[0]+"\data\env.bat")} -Args $lesDestDir

I see it execute as it echoes its work in my powershell window, but subsequent calls to the installation script ie:

Invoke-Command -session $session {perl ".\rollout-2010.pl " $args[0] " NC"} -Args $rollout

immediately exit saying the various system variables it uses have not been set. Can someone explain to me the scope of the system variables? Do they cease to exist after the invoke-command completes? Do I need to string together the two script calls in a single invoke-command so that the second script can access the system variables or something like that?

JDH
  • 2,618
  • 5
  • 38
  • 48

2 Answers2

3

Changes made using the SET command are NOT permanent, they apply to the current cmd process only and remain until the cmd process is terminated.

If possible set the environment variable using powershell syntax:

Invoke-Command -session $session {$env:myvar = 1}

Alternatively you could string the commands using the cmd command separator & like this:

Invoke-Command -session $session {cmd /k "set myvar = 1" `& "set"}
jon Z
  • 15,838
  • 1
  • 33
  • 35
  • Maybe I'm missing something, but shouldn't the following echo a value of 1 then: Invoke-Command -session $session {cmd /k "set myvar=1" `& "echo %myvar%"} It produces no output. – JDH Jul 29 '12 at 15:27
  • 1
    Variable expansion occurs when the command is read (before it is set in your command). To delay the expansion of the variable add the /v switch when calling cmd.exe and use ! instead of %: Invoke-Command -session $session {cmd /v /k "set mytar=2 & echo !mytar!"} – jon Z Jul 29 '12 at 16:31
  • Thank you for the examples and clear explanation. I was able to accomplish what I was working on. – JDH Jul 29 '12 at 20:38
0

Yes, you need to string them together. The environment variables are being set in the first cmd session which exits, then a second one is started without them.

Mike Shepard
  • 17,466
  • 6
  • 51
  • 69