PowerShell-V5调用Webrequest添加了2个标头授权标题,并接受接受标头



我正在尝试创建一个脚本,该脚本将使用powerShell和Indoke-webrequest自动升级NSX,以利用NSX Manager的API调用。我使用脚本,但是脚本的某些部分我需要检查并匹配响应中的一些数据。实际上,NSX API响应将以XML格式为90%,但有时可能是JSON。如果响应以JSON格式出现,我的匹配将无法正常工作,并且脚本的某些部分也无法正常工作,因为它期望XML并且无法将JSON转换为XML。

我知道,从PowerShell V4开始,您可以添加Accept标头,但问题是我已经在使用一个标头进行授权。

是否可以在PowerShell中添加多个标头,如果是的,它将如何。

下面是我拥有的脚本的一部分,它将检查已部署的NSX的当前版本。因此,它将与将显示版本的响应中的值匹配。

#Variables to be used within the script.
[CmdletBinding()]
$NSXUsername = "admin"
$NSXPassword = "VMware1!"
$uriP = "https://HQ-NSX-01a.nsx.gss"

# Start time.
$startclock = (Get-Date)
Write-Host -BackgroundColor:Black -ForegroundColor:Green "Hello"
Write-Host -BackgroundColor:Black -ForegroundColor:Green "This script will help you to automate a full NSX environment deployment"
Write-Host -BackgroundColor:Black -ForegroundColor:Green "FULL NSX Tier Deployment for Single-VC is starting, This Deployment proccess will take an average of 60 min
========================================================================================
                                 "


# Create NSX authorization string and store in $head and used in API Calls
# $nsxcreds = New-Object System.Management.Automation.PSCredential $NSXUsername,$NSXPassword
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($NSXUsername + ":" + $NSXPassword))
$head = @{"Authorization"="Basic $auth"}
# Allow untrusted SSL certs else will error out
    add-type @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;
        public class TrustAllCertsPolicy : ICertificatePolicy {
            public bool CheckValidationResult(
                ServicePoint srvPoint, X509Certificate certificate,
                WebRequest request, int certificateProblem) {
                return true;
            }
        }
"@
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

################
#Start of Script
################
###########################################
# Checking the current deployed NSX Version
###########################################
    Write-Host -BackgroundColor:Black -ForegroundColor:Green "      Checking the current deployed version of the NSX
                             "

    $r = Invoke-WebRequest -Uri "$uriP/api/1.0/appliance-management/global/info" -Method:Get -Headers $head -ContentType "application/xml" -ErrorAction:Stop -TimeoutSec 60
    $nsxbn = ([xml]$r.Content).globalInfo.versionInfo.buildNumber
    if ($nsxbn -match "2691049") {$nsxcv = "6.1.4"}
    elseif ($nsxbn -match "3102213") {$nsxcv = "6.1.5"}
    elseif ($nsxbn -match "3615148") {$nsxcv = "6.1.6"}
    elseif ($nsxbn -match "3949567") {$nsxcv = "6.1.7"}
    elseif ($nsxbn -match "2986609") {$nsxcv = "6.2.0"}
    elseif ($nsxbn -match "3300239") {$nsxcv = "6.2.1"}
    elseif ($nsxbn -match "3496286") {$nsxcv = "6.2.1a"}
    elseif ($nsxbn -match "3604087") {$nsxcv = "6.2.2"}
    elseif ($nsxbn -match "3638734") {$nsxcv = "6.2.2a"}
    elseif ($nsxbn -match "3755950") {$nsxcv = "6.2.2b"}
    elseif ($nsxbn -match "3979471") {$nsxcv = "6.2.3"}
    elseif ($nsxbn -match "4167369") {$nsxcv = "6.2.3a"}
    elseif ($nsxbn -match "4287432") {$nsxcv = "6.2.3b"}
    elseif ($nsxbn -match "4292526") {$nsxcv = "6.2.4"}
    elseif ($nsxbn -match "4818372") {$nsxcv = "6.2.5"}
    elseif ($nsxbn -match "4977495") {$nsxcv = "6.2.6"}
    elseif ($nsxbn -match "5007049") {$nsxcv = "6.3.0"}
    elseif ($nsxbn -match "5124716") {$nsxcv = "6.3.1"}
    else {
    Write-host -BackgroundColor:Black -ForegroundColor:Red "       Unable to retrieve the NSX version, This is either due to the current version is unknown to this script or the NSX Manager is powered off. Please check and try again."
    exit
    }
    Write-Host -BackgroundColor:Black -ForegroundColor:Green "      Current version of NSX deployed and to be upgraded is $nsxcv
                             "

响应如果以XML格式为下面的响应,我将在版本上匹配。

<?xml version="1.0" encoding="UTF-8"?>
<globalInfo>
    <currentLoggedInUser>admin</currentLoggedInUser>
    <versionInfo>
        <majorVersion>6</majorVersion>
        <minorVersion>1</minorVersion>
        <patchVersion>5</patchVersion>
        <buildNumber>3102213</buildNumber>    <<<--- this is my match
    </versionInfo>
</globalInfo>

,如果响应的格式为90%,则以上脚本将正常工作,但是如果是JSON,我将遇到以下错误,并且脚本将退出。

Cannot convert value "{"currentLoggedInUser":"admin","versionInfo":{"majorVersion":"6","minorVersion":"1","patchVersion":"5","buildNumber":"3102213"}}" 
to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong 
type."
At C:UsersAdministratorDesktopScripts  FolderNSX-Auto-Upgrade-Single.ps1:68 char:2
+     $nsxbn = ([xml]$r.Content).globalInfo.versionInfo.buildNumber
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastToXmlDocument

您的帮助非常感谢。

谢谢。

我收集您打算通过PowerShell将多个标头添加到REST API调用中。而不是添加这样的标题,

$head = @{"Authorization"="Basic $auth"}
Invoke-WebRequest -Uri "$uriP/api/1.0/appliance-management/global/info" -Method:Get -Headers $head -ContentType "application/xml" -ErrorAction:Stop -TimeoutSec 60

您可以像这样添加它们

Invoke-WebRequest -Uri "$uriP/api/1.0/appliance-management/global/info" -Method:Get -Headers @{"Authorization"="Basic $auth"; "Accept"="application/xml"} -ContentType "application/xml" -ErrorAction:Stop -TimeoutSec 60

我找到了答案并在此处发布。

如果您更改了标头零件以添加更多标头,则下面将起作用:

$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($NSXUsername + ":" + $NSXPassword))
$head = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$head = @{}
$head.Add("Authorization","Basic $auth")
$head.Add("Accept","application/xml")

因此,当我将其添加到脚本中时,它可以正常工作,并且要确认它一次使用" Application/XML",而另一个则与Accept" application/json"并打印了输出。

因此,首先接受"应用程序/XML"

脚本:

#Variables to be used within the script.
[CmdletBinding()]
$NSXUsername = "admin"
$NSXPassword = "VMware1!"
$uriP = "https://HQ-NSX-01a.nsx.gss"
# Start time.
$startclock = (Get-Date)
# Create NSX authorization string and store in $head and used in API Calls
# $nsxcreds = New-Object System.Management.Automation.PSCredential $NSXUsername,$NSXPassword
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($NSXUsername + ":" + $NSXPassword))
$head = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$head = @{}
$head.Add("Authorization","Basic $auth")
$head.Add("Accept","application/xml")
# Allow untrusted SSL certs else will error out
    add-type @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;
        public class TrustAllCertsPolicy : ICertificatePolicy {
            public bool CheckValidationResult(
                ServicePoint srvPoint, X509Certificate certificate,
                WebRequest request, int certificateProblem) {
                return true;
            }
        }
"@
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
$r = Invoke-WebRequest -Uri "$uriP/api/1.0/appliance-management/global/info" -Method:Get -Headers $head -ContentType "application/xml" -ErrorAction:Stop -TimeoutSec 60

    Write-host -BackgroundColor:Black -ForegroundColor:Red "$r"

我得到以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<globalInfo><currentLoggedInUser>admin</currentLoggedInUser><versionInfo><majorVersion>6</majorVersion><minorVersion>1</minorVersion><patchVersion>5</patchVersion><
buildNumber>3102213</buildNumber></versionInfo></globalInfo>

如果我将标题变量更改为以下(仅接受JSON):

$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($NSXUsername + ":" + $NSXPassword))
$head = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$head = @{}
$head.Add("Authorization","Basic $auth")
$head.Add("Accept","application/json")

我得到以下内容:

{"currentLoggedInUser":"admin","versionInfo":{"majorVersion":"6","minorVersion":"1","patchVersion":"5","buildNumber":"3102213"}}

因此,基于我问题的解决方案是将原始脚本中的标题变量(在上面的问题中发布)更改为以下内容,这将正常工作:

$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($NSXUsername + ":" + $NSXPassword))
$head = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$head = @{}
$head.Add("Authorization","Basic $auth")
$head.Add("Accept","application/xml")

最新更新