Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: script to find allowedServerVariables in applicationHost.config check for duplicate

I am trying add a new server variable

Add-WebConfiguration /system.webServer/rewrite/allowedServerVariables -atIndex 0 -value @{name="HTTP_COOKIE"}

but I am getting following error

Add-WebConfigurationProperty : Filename: 
Error: Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'Test'
At line:1 char:1
+ Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Add-WebConfigurationProperty], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.IIs.PowerShell.Provider.AddConfigurationPropertyCommand

I could suppress using try catch block but would like to check if the variable already exists and skip Adding if it already exists.

Can anyone let me know how I can do this check?

like image 737
RajGan Avatar asked Jan 31 '19 15:01

RajGan


2 Answers

Try adding the following check for example:

$path = "/system.webServer/rewrite/allowedServerVariables"
$value = "HTTP_COOKIE"
if ((Get-WebConfiguration $path).Collection.Name -notcontains $value) {
    Add-WebConfiguration $path -AtIndex 0 -Value @{ name = $value }
}
like image 187
marsze Avatar answered Oct 01 '22 12:10

marsze


@marsze way has done using Get-WebConfiguration.

my answer is using Get-WebConfigurationProperty. Both will work.

Write-Host "Getting allowed server variables..."
$allowedServerVariables = Get-WebConfigurationProperty -PSPath "MACHINE/WEBROOT/APPHOST" -filter "system.webServer/rewrite/allowedServerVariables/add" -Name name
Write-Host "Found $($allowedServerVariables.Length)..."

if ( ($allowedServerVariables -eq $null) -or ( $allowedServerVariables | ?{ $_.Value -eq "HTTP_COOKIE1" } ).Length -eq 0 ) {
    #Configure IIS To Allow 'HTTPS' as a server variable - Must be done at a applicationhosts.config level
    Write-Host "Adding HTTPS to allowed server variables..."
    Add-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST"  -filter "system.webServer/rewrite/allowedServerVariables" -name "." -value @{name='HTTP_COOKIE1'}
}

Write-Host "Getting allowed server variables...Finished"
like image 25
RajGan Avatar answered Oct 01 '22 14:10

RajGan