LoginSignup
0
2

More than 5 years have passed since last update.

powershell chatwork用 2.0系とそれ以上対応

Posted at

Chatworkにメッセージ投げる関数

Invoke-WebRequest 使えない2系にも一応対応した。

やっつけでやってる部分も有るので、汚い所はスルーで。


## Chatwork用
$apitoken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$roomid = "12345678"

$toAddress = "[To:XXXX] てすとさん"

$chatworkUri = "https://api.chatwork.com/v2/rooms/{0}/messages" -f $roomid


# chatwork通知
function SendChatworkMsg([string] $title, [string] $msg){
    # powershell 2.0 対応
    if($PSVersionTable.PSVersion.Major -ge 2){
        SendChatworkMsg_2 -title $title -msg $msg
        return  
    }
    $toAddress = setToMsg
    if(![string]::IsNullOrEmpty($toAddress)){
        $msg = $toAddress + "`n" + $msg
    }

    $r = Invoke-WebRequest -Uri $chatworkUri `
         -Method POST `
         -Body @{"body" = "[info][title]$title[/title]$msg[/info]"} `
         -Headers @{"X-ChatWorkToken" = $apitoken}

}

# PS 2.0向け
function SendChatworkMsg_2{ 
    param( 
         [string] $title, [string] $msg
    ) 

    $toAddress = setToMsg
    if(![string]::IsNullOrEmpty($toAddress)){
        $msg = $toAddress + "`n" + $msg
    }

    $fields=new-object System.Collections.Specialized.NameValueCollection 
    $fields.Add("body","[info][title]$title[/title]$msg[/info]") 

    $wc = new-object System.Net.WebClient 
    $wc.Headers.Add("X-ChatWorkToken",$apitoken) 


     Try{ 
          #$wc.UploadValues($chatworkUri, $fields) 
          $res = $wc.UploadValues($chatworkUri, "POST", $fields) 
          #Write-Host $res
     } 
     Catch{ 
          throw $_ #rethrow the exception 
     } 
} 

function setToMsg{
    return $toAddress
}


#TEST
#SendChatworkMsg "TEST" "MSG"
#SendChatworkMsg_2 "TEST" "MSG"

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2