iisapplication-poolappcmd

Using appcmd.exe, is there away to ADD OR UPDATE an IIS app pool's environment variable?


I know I can add an environment variable to an app pool using this:

appcmd.exe set config /section:system.applicationHost/applicationPools /+"[name='myAppPool'].environmentVariables.[name='myvar',value='myvalue']"

But this fails if the environment variable already exists.

There's also a command to set the value of an already existing environment variable, but it fails if the environment variable doesn't already exist.

Is there a command that works in both cases? i.e. add the variable if it doesn't exist, update it if it does?


Solution

  • I think you can achieve your needs by creating a script. For example, you can use the following powershell script to first check whether the environment variable exists, if the environment variable already exists, update its variable value, and if not, add the variable.

    # Check if the environment variable already exists
    $existingEnv = Get-WebConfigurationProperty -Filter "system.applicationHost/applicationPools/add[@name='myAppPool']/environmentVariables/add[@name='myvar']" -Name value -PSPath "IIS:\"
        
    if ($existingEnv) {
       # If the environment variable already exists, update its value
       Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.applicationHost/applicationPools/add[@name='myAppPool']/environmentVariables/add[@name='myvar']" -name "value" -value "myvalue"
    }
    else {
       # Add the environment variable if it doesn't exist
       Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.applicationHost/applicationPools/add[@name='myAppPool']/environmentVariables" -name "." -value @{name='myvar';value='myvalue'}
    }