2016-11-15 35 views
0

我有VBA代碼工作正常:未經授權的錯誤在PowerShell中,但不是在VBA

Dim sURL As String 
Dim sEnv As String 
Dim xmlhtp As New MSXML2.XMLHTTP 
Dim xmlDoc As New DOMDocument 
Public Const tamhost As String = "cadd.ad2.gt.au:9045" 

sURL = "http://" & tamhost & "/mweb/services/AEXTSYS4_QueryAssets" 

sEnv = "<?xml version=""1.0"" encoding=""utf-8""?>" 
sEnv = sEnv & "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:max=""http://www.asdf.com/asdf"">" 
sEnv = sEnv & " <soap:Body>" 
sEnv = sEnv & "  <max:QueryASSET>" 
sEnv = sEnv & "   <max:ASSETQuery>" 
sEnv = sEnv & "    <max:ASSET>" 
sEnv = sEnv & "     <max:ASSETTAG operator=""="">asdf45412</max:ASSETTAG>" 
sEnv = sEnv & "    </max:ASSET>" 
sEnv = sEnv & "   </max:ASSETQuery>" 
sEnv = sEnv & "  </max:QueryASSET>" 
sEnv = sEnv & " </soap:Body>" 
sEnv = sEnv & "</soap:Envelope>" 


' invoke the service 
With xmlhtp 
.Open "post", sURL, False 
.setRequestHeader "Host", tamhost 
.setRequestHeader "Content-Type", "application/soap+xml;charset=UTF-8;action=""urn:processDocument""" 
.send sEnv 
xmlDoc.LoadXML .responseText 
End With 

我可以看到.responseText

但是一個有效的XML字符串時,我這個代碼轉換爲PowerShell的:

$sEnv = "<?xml version=""1.0"" encoding=""utf-8""?>" 

$sEnv += "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:max=""http://www.asdf.com/asdf"">" 
$sEnv += " <soap:Body>" 
$sEnv += "  <max:QueryASSET>" 
$sEnv += "   <max:ASSETQuery>" 
$sEnv += "    <max:ASSET>" 
$sEnv += "     <max:ASSETTAG operator=""="">asdf45412</max:ASSETTAG>" 
$sEnv += "    </max:ASSET>" 
$sEnv += "   </max:ASSETQuery>" 
$sEnv += "  </max:QueryASSET>" 
$sEnv += " </soap:Body>" 
$sEnv += "</soap:Envelope>" 

$soapEnvelopeXml = New-Object 'System.Xml.XmlDocument' 
$soapEnvelopeXml.LoadXml($sEnv) 

$tamhost = 'cadd.ad2.gt.au:9045' 
$sURL = "http://$tamhost/mweb/services/AEXTSYS4_QueryAssets" 

$request = [System.Net.HttpWebRequest]([System.Net.WebRequest]::Create($sURL)) 
$request.Host = $tamhost 
$request.ContentType = 'application/soap+xml;charset=UTF-8;action=""urn:processDocument""' 
$request.Method = 'POST' 

$stream = $request.GetRequestStream() 
$soapEnvelopeXml.Save($stream) 
$stream.Close() 

$response = $request.GetResponse() #"The remote server returned an error: (401) Unauthorized." 

我得到了401未經授權的錯誤。

爲什麼它不能在Powershell中工作,我該如何解決它?

回答

0

這解決了這一問題:

$request = [System.Activator]::CreateInstance([System.Type]::GetTypeFromProgID('MSXML2.XMLHTTP')) 

$request.Open('POST', $sURL, $false) 
$request.SetRequestHeader('Host', $tamhost) 
$request.SetRequestHeader('Content-Type', "application/soap+xml;charset=UTF-8;action=""urn:processDocument""") 
$request.Send($sEnv)