Raj*_*Gan 5 .net c# windows asp.net powershell
我正在尝试添加一个新的服务器变量
Add-WebConfiguration /system.webServer/rewrite/allowedServerVariables -atIndex 0 -value @{name="HTTP_COOKIE"}
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误
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
Run Code Online (Sandbox Code Playgroud)
我可以使用 try catch 块进行抑制,但想检查变量是否已经存在,如果它已经存在则跳过添加。
谁能告诉我如何进行这项检查?
例如,尝试添加以下检查:
$path = "/system.webServer/rewrite/allowedServerVariables"
$value = "HTTP_COOKIE"
if ((Get-WebConfiguration $path).Collection.Name -notcontains $value) {
Add-WebConfiguration $path -AtIndex 0 -Value @{ name = $value }
}
Run Code Online (Sandbox Code Playgroud)
@marsze 方式已使用 Get-WebConfiguration 完成。
我的答案是使用 Get-WebConfigurationProperty。两者都会起作用。
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"
Run Code Online (Sandbox Code Playgroud)