[PowerShell] 進行HTTP request

有專案要執行排程工作, 其實可以用quntize 實現, 但管理上會出現分散而難以管理的問題, 在有automation software 前, 唯有利用 task scheduler 作過渡.

# Name            : HttpPost.ps1
# Author          : Ling
# Description     : Connect MAP Backend service to execute task.
#
# Syntax (in cmd) : Powershell.exe -ExecutionPolicy ByPass HttpPost.ps1 <<Web Service Endpoint URL>> <<JSON parameter>>

[string] $url=$args[0]
[string] $requestBody=$args[1]
[string] $logFile="C:\log\HttpPost.log"
[string] $stdOutputMessage=""

function Write-Log {
    Param([string]$eventType, [string]$message)
    $currentDateTime=Get-Date
    $logContent="["+$currentDateTime+"] ["+$eventType+"] "+$message
    echo($logContent)
    add-content $logFile -Value $logContent
    #Write-EventLog -LogName "PS HttpPost" -Source "Application" -EventID 3001 -EntryType $eventType -Message $message -Category 1 -RawData 10,20
}

try {
    $stdOutputMessage="HttpPost start. URL:"+$url+"; Parameter:"+$requestBody
    Write-Log -eventType "Information" -message $stdOutputMessage
    $response=Invoke-RestMethod -Uri $url -ContentType "application/json" -Method POST -Body $requestBody

    if($response.success) {
        echo($response.message)
        Write-Log "Information" $response.message
    } else {
        throw "Response fail in request. "+$response.message
    }
} catch {
    $stdOutputMessage=$_.Exception.Message
    Write-Log "Error" $stdOutputMessage
} finally {
    Write-Log "Information" "HttpPost executed.";
}

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.