0

I've got a yaml pipeline that needs to set (create if not there) a windows environment variable on a VM that is to be used by another program on the VM. How do I go about doing that?

I've tried looking at this question (amongst other articles) but none of the answers worked. They either needed the .NET SDK installed or didn't fail but didn't create the variable. I get the impression this should be possible using powershell, so very similar to one of the answers in that question I tried this:

- task: PowerShell@2
      displayName: Set environment variables.
      inputs:
        targetType: 'inline'
        script: |
          Write-Host "##vso[task.setvariable variable=MY_KEY;]$(TestSecret)"

Like I say, this doesn't fail, but when I check the VM environment variables 'MY_KEY' doesn't exist.

UPDATE

Following the suggestion below from Lee_Dailey I tried the following:

- task: PowerShell@2
      displayName: Set environment variables.
      inputs:
        targetType: 'inline'
        script: | 
          [System.Environment]::SetEnvironmentVariable("MY_KEY", "$($env:TestSecret)", "Machine")
      env:
        TestSecret: $(TestSecret)

I also tried replacing the actual value of the key with just "testKey" rather than using a variable, as well as setting [Environment] rather than [System.Environment]. In all cases the pipeline ran without errors but no environment / system variable was created on the VM with the name MY_KEY.

I double checked it was running this on the right machine by writing the computer name to the console, so I know it's not somehow doing this on another machine.

sr28
  • 4,728
  • 5
  • 36
  • 67
  • take a look at `[System.Environment]::SetEnvironmentVariable()` - that will set a env var that _can_ be visible machine-wide. – Lee_Dailey May 18 '22 at 16:45
  • @Lee_Dailey - I've tried your suggestion but unfortunately this still doesn't create the variable. If you have any other ideas please let me know. – sr28 May 19 '22 at 07:38
  • 1
    i see that you got it working as needed. great! [*grin*] – Lee_Dailey May 19 '22 at 14:47

1 Answers1

0

Turns out one of my earlier attempts actually did work. However, the way I was checking the variables wasn't picking up on it (command prompt using 'set' to read them all, didn't restart the session). So I checked through the system settings GUI and found it was getting set after all. I ended up with this:

- task: PowerShell@2
      displayName: Set environment variables.
      inputs:
        targetType: 'inline'
        script: | 
          [System.Environment]::SetEnvironmentVariable("MY_KEY", "$(TestSecret)", [System.EnvironmentVariableTarget]::Machine)
sr28
  • 4,728
  • 5
  • 36
  • 67