PowerShell
PowerShell

Reputation: 2081

Invoke-WebRequest equivalent in PowerShell v2

Can some one help me with the powershell v2 version of the below cmdlet.

$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

Upvotes: 17

Views: 45307

Answers (3)

This method downloads binary content:

# 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 

Upvotes: 1

David Brabant
David Brabant

Reputation: 43579

$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()

Upvotes: 16

user189198
user189198

Reputation:

Here, give this a shot. I provided some in-line comments. Bottom line, you're going to want to use the HttpWebRequest class from the .NET Base Class Library (BCL) to achieve what you're after.

$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);

Upvotes: 2

Related Questions