Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > MS Windows > Powershell script POST with basic authorization


Автор: Wazluk 2.9.2014, 00:57
Все привет!
В powershell-е я совсем не силен, но очень нужно написать скрипт который шлет JSON данные с basic authorization.
Помогите довести его до ума.

Код

param($Credentials = $(Get-Credential), $BaseURI = "http://localhost:2990/jira")


#New-RestItem "$BaseURI/rest/api/2/issue/" -Data @{"JSON" = '{"fields":{"project":{"key":"TES"},"summary":"REST OLOLO","description":"Creating of an issue using project keys and issue type names using the REST API","issuetype":{"name": "Bug"}}}'}

#[CmdletBinding()]

[String]$Url = "$BaseURI/rest/api/2/issue/"
[HashTable]$Data = @{"JSON" = '{"fields":{"project":{"key":"TES"},"summary":"REST OLOLO","description":"Creating of an issue using project keys and issue type names using the REST API","issuetype":{"name": "Bug"}}}'}
[TimeSpan]$Timeout = [System.TimeSpan]::FromMinutes(1)
    
    Add-Type -AssemblyName System.Web
    $formData = [System.Web.HttpUtility]::ParseQueryString("")  
    foreach($key in $Data.Keys){
        $formData.Add($key, $Data[$key])        
    }
    Write-Verbose $formData.ToString()
    $reqBody = [System.Text.Encoding]::Default.GetBytes($formData.ToString())   

    try{
        $req = [System.Net.WebRequest]::Create($Url);
        
        #$b64 = ConvertTo-Base64 "$($Credentials.UserName):$($Credentials.Password)"
        #$creds = "Basic $b64"
        #$req.Headers.Add("Authorization", "Basic $creds")
        #ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
        $credentialCache = New-Object -TypeName System.Net.CredentialCache;
        $urrl = New-Object -TypeName System.Uri $Url;
        $crr = New-Object -TypeName System.Net.NetworkCredential $Credentials.UserName $Credentials.Password;
        $credentialCache.Add($urrl, "Basic", $crr);
        
        $req.Credentials = credentialCache;
        $req.PreAuthenticate = $true
        
        $req.Method = "POST"
        $req.ContentType = "application/x-www-form-urlencoded"      
        $req.Timeout = $Timeout.TotalMilliseconds
        $reqStream = $req.GetRequestStream()        
        $reqStream.Write($reqBody, 0, $reqBody.Length)
        $reqStream.Close()

        $resp = $req.GetResponse()
        Write-Verbose $resp
        Write-Output $resp.StatusCode
    }
    catch [System.Net.WebException]{
        if ($_.Exception -ne $null -and $_.Exception.Response -ne $null) {
            $errorResult = $_.Exception.Response.GetResponseStream()
            $errorText = (New-Object System.IO.StreamReader($errorResult)).ReadToEnd()
            Write-Warning "The remote server response: $errorText"
            Write-Output $_.Exception.Response.StatusCode
        } else {
            throw $_
        }
    }   


function ConvertTo-Base64($string) {
   $bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
   $encoded = [System.Convert]::ToBase64String($bytes);
 
   return $encoded;
}



Выдает след. ошибку:

Код

New-Object : A positional parameter cannot be found that accepts argument 'System.Security.SecureString'.
At C:\Users\a_triliser\Desktop\powershell\test.ps1:34 char:26
+         $crr = New-Object <<<<  -TypeName System.Net.NetworkCredential $Credentials.UserName $Credentials.Password;
    + CategoryInfo          : InvalidArgument: (:) [New-Object], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand


Не понимаю что нужно сделать чтоб он заработал. Поможите плиз.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)