Set IIS environment variable through script

1.4k views Asked by At

I want to add/delete/edit IIS, asp.net core website environment variables in an automated way through appcmd/batch file or PowerShell script, not only one website's variable but on bulk operation. although I can do this one by using IIS UI

enter image description here

Although I can add environment variable by using appcmd

appcmd.exe reset config "variable" -section:system.webServer/aspNetCore /+"environmentVariables.[name='foo',value='bar']"

I could not find a way for add/delete/update multiple websites environment values by just clicking single button instead of going each website's configuration setting to set multiple values, After that I can use that inline script in Azure DevOps pipeline

1

There are 1 answers

4
Bruce Zhang On BEST ANSWER

You can write multiple powershell into a file and execute it. Here is an example for reference.

  1. Create a file and named "xxx.ps1".

  2. Write multiple powershell statements.

    Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Core Web Site'  -filter "system.webServer/aspNetCore/environmentVariables" -name "." -value @{name='foo';value='bar'}
    
    
    Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Core Web Site'  -filter "system.webServer/aspNetCore/environmentVariables" -name "." -value @{name='doc';value='qwe'}
    
    
    Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter "system.webServer/aspNetCore/environmentVariables" -name "." -value @{name='foo';value='bar'}
    
    
    Write-Output ('Execute succeed')
    

    Edit and remove enironment value

    Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Core Web Site'  -filter "system.webServer/aspNetCore/environmentVariables/environmentVariable[@name='foo' and @value='bar']" -name "name" -value "foo2"
    
    
    Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Core Web Site'  -filter "system.webServer/aspNetCore/environmentVariables/environmentVariable[@name='foo' and @value='bar']" -name "value" -value "bar2"
    
    
    Remove-WebConfigurationProperty  -pspath 'MACHINE/WEBROOT/APPHOST/Core Web Site'  -filter "system.webServer/aspNetCore/environmentVariables" -name "." -AtElement @{name='foo1';value='bar1'}
    
  3. Open powershell to execute the file(file's path + name).

    PS C:\WINDOWS\system32> & "D:\floder1\xxx.ps1"