PowerShell v2中的Invoke-WebRequest等效项

时间:2014-08-04 14:10:28

标签: powershell

有人可以帮助我使用下面cmdlet的powershell v2版本。

$body = 
"<wInput>
  <uInputValues>
   <uInputEntry value='$arg' key='stringArgument'/>
  </uInputValues>
  <eDateAndTime></eDateAndTime>
  <comments></comments> 
</wInput>"

$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)

$output = Invoke-WebRequest -Uri $URI1 -Credential $credential -Method Post -ContentType application/xml -Body $body

3 个答案:

答案 0 :(得分:12)

$URI1 = "<your uri>"

$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)

$request = [System.Net.WebRequest]::Create($URI1)
$request.ContentType = "application/xml"
$request.Method = "POST"
$request.Credentials = $credential

# $request | Get-Member  for a list of methods and properties 

try
{
    $requestStream = $request.GetRequestStream()
    $streamWriter = New-Object System.IO.StreamWriter($requestStream)
    $streamWriter.Write($body)
}

finally
{
    if ($null -ne $streamWriter) { $streamWriter.Dispose() }
    if ($null -ne $requestStream) { $requestStream.Dispose() }
}

$res = $request.GetResponse()

答案 1 :(得分:2)

在这里,试一试。我提供了一些在线评论。最重要的是,您将要使用.NET基类库(BCL)中的HttpWebRequest类来实现您的目标。

$Body = @"
<wInput>
  <uInputValues>
   <uInputEntry value='$arg' key='stringArgument'/>
  </uInputValues>
  <eDateAndTime></eDateAndTime>
  <comments></comments> 
</wInput>
"@;

# Convert the message body to a byte array
$BodyBytes = [System.Text.Encoding]::UTF8.GetBytes($Body);
# Set the URI of the web service
$URI = [System.Uri]'http://www.google.com';

# Create a new web request
$WebRequest = [System.Net.HttpWebRequest]::CreateHttp($URI);
# Set the HTTP method
$WebRequest.Method = 'POST';
# Set the MIME type
$WebRequest.ContentType = 'application/xml';
# Set the credential for the web service
$WebRequest.Credentials = Get-Credential;
# Write the message body to the request stream
$WebRequest.GetRequestStream().Write($BodyBytes, 0, $BodyBytes.Length);

答案 2 :(得分:1)

此方法下载二进制内容:

# PowerShell 2 version
$WebRequest=New-Object System.Net.WebClient
$WebRequest.UseDefaultCredentials=$true
#$WebRequest.Credentials=(Get-Credential)
$Data=$WebRequest.DownloadData("http://<url>")
[System.IO.File]::WriteAllBytes("<full path of file>",$Data)

# PowerShell 5 version
Invoke-WebRequest -Uri "http://<url>" -OutFile "<full path of file>" -UseDefaultCredentials -ContentType