Powershell为powershell 2.0调用webrequest

时间:2017-01-11 08:10:58

标签: powershell

我在powershell 5.0中创建了一个脚本,用于检索网站中的数据并将其放入文件中。以下代码适用于Windows 7及更高版本,因为它们都具有.net framework 5.0。现在我被告知我需要在较低的Windows操作系统(如XP)上运行。 XP中的powershells是2.0,而microsoft已经结束了对XP的支持。我需要一个PowerShell 2.0代码,其行为与我在5.0中编写的代码相同:

$number = 1000
$startdate = 2017-01-05
$enddate = 2017-01-11
invoke-webrequest -Uri http://192.168.1.1/form/Download?uid=$number"&"sdate=$startdate"&"edate=$enddate -OutFile D:\Timekeeping\dtr\data.dat -PassThru

1 个答案:

答案 0 :(得分:1)

替代方法没有直接的cmdlet:

但你可以使用以下内容:

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

基本上我们正在使用Dot Net Class:

$request = [System.Net.WebRequest]::Create("$url")
$request.ContentType='application/json; charset=utf-8'
$request.GetResponse()

您可以流式解析它:

$ResponseStream = $Response.GetResponseStream()
$ReadStream = New-Object System.IO.StreamReader $ResponseStream
$Data=$ReadStream.ReadToEnd()

希望它有所帮助。