无法使用PowerShell通过API发布请求

时间:2017-11-09 09:01:51

标签: .net api powershell

我们有一个函数,它有助于回发我们​​在调用时运行的应用程序。当客户端运行PowerShell v3.0或更高版本时,这非常有效,但是我们有一个混合版本,现在没有可行的升级PowerShell。我已经看到你可以使用.NET以相同的方式发布xml,但是我不能让它工作。

这是适用的版本:

function SetTaskRealTimeStatus()
{
    param($pRealTimeStatusId, $pResourceGuid, $pNewStatus)

    $url = 'http://server001/myappname/api/resource/';
    $url = $url +  $pResourceGuid + '/task/' + $realTimeStatusId + '/status/'+ $pNewStatus;

    Write-Host ("Sending request: $url") ;

    # Returns Guid of task history record that is created. Empty guid means db call failed
    # Invalid inputs will return BadRequest response
    Invoke-RestMethod -Uri $URL -Method Post
}

这是我的版本不起作用:

function SetTaskRealTimeStatus()
{
    param($pRealTimeStatusId, $pResourceGuid, $pNewStatus)

    $url = 'http://server001/myappname/api/resource/';
    $urlCombined = $url +  $pResourceGuid + '/task/' + $pRealTimeStatusId + '/status/'+ $pNewStatus;

    Write-Host ("Sending request: $urlCombined") ;

    # Returns Guid of task history record that is created. Empty guid means db call failed
    # Invalid inputs will return BadRequest response

    #Used for PowerShell version 2.0
    $WebRequest = [System.Net.WebRequest]::Create("$urlCombined")
    $WebRequest.Method = "POST"
    $WebRequest.ContentType = "application/xml"
    $WebRequest.UseDefaultCredentials = $true
    $Response = $WebRequest.GetResponse() 
    $ResponseStream = $Response.GetResponseStream()
    $ReadStream = New-Object System.IO.StreamReader $ResponseStream
    $Data=$ReadStream.ReadToEnd()
    $Request.Timeout = 10000;

    #Invoke-RestMethod -Uri $urlCombined -Method Post
}

过去函数的参数工作正常,因为它们适用于第一个版本。

1 个答案:

答案 0 :(得分:0)

我设法让功能按要求运行:

function SetTaskRealTimeStatus()
{

    param($setID, $pResourceGuid, $pNewStatus)


    $url = 'http://server001/myapplication/api/resource/';
    $urlCombined = $url +  $pResourceGuid + '/task/' + $setID + '/status/' + $pNewStatus;

    Write-Host ("Sending request: $urlCombined") ;

    # Returns Guid of task history record that is created. Empty guid means db call failed
    # Invalid inputs will return BadRequest response

    #Used for PowerShell version 2.0

    $WebRequest = [System.Net.WebRequest]::Create("$urlCombined")
    $body = "$pNewStatus"
    $encodedContent = [System.Text.Encoding]::UTF8.GetBytes($body)
    $WebRequest.Method = "POST"
    $WebRequest.ContentType = "application/xml"
    $WebRequest.UseDefaultCredentials = $true
    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($encodedContent, 0, $encodedContent.length)  
    [System.Net.WebResponse] $response = $webRequest.GetResponse();
    $response.close()
    $requestStream.Close()


    #used for PowerShell Version 3.0 and above
    #Invoke-RestMethod -Uri $urlCombined -Method Post
}