接続の確立
CData Cmdlets ユーザーは、データモジュールをインストールし、接続プロパティを設定してスクリプトを開始できます。このセクションでは、CSV インポートおよびエクスポートcmdlet などのネイティブPowerShell cmdlet でFreshDesk Cmdlets を使用する例を示します。
Connecting to Freshdesk
Freshdesk makes use of basic authentication. To connect to data, set the following connection properties:
- Domain: Set this to the domain associated with your Freshdesk account. For example, in your URL, https://{domainValue}.freshdesk.com, thus the connection string should be:
Domain=domainValue
- APIKey: Set this to the API key associated with your Freshdesk account. To retrieve your API key, log in to your support Portal. Click the profile picture in the upper-right corner and select the profile settings page. The API key is available below the change password section to the right.
接続オブジェクトの作成
Connect-FreshDesk cmdlet を使って、別のcmdlet に渡すことができる接続オブジェクトを作成します。
$conn = Connect-FreshDesk -Domain "MyDomain" -APIKey "myAPIKey"
データの取得
Select-FreshDesk cmdlet はデータを取得するためのネイティブなPowerShell インターフェースを提供します。
$results = Select-FreshDesk -Connection $conn -Table "Tickets" -Columns @("Id, Name") -Where "Status='2'"
Invoke-FreshDesk cmdlet はSQL インターフェースを提供します。このcmdlet を使うと、Query パラメータを介してSQL クエリを実行できます。
cmdlet 出力のパイプ処理
cmdlet は行オブジェクトをパイプラインに一度に一行ずつ返します。以下は、結果をCSV ファイルにエクスポートします。
Select-FreshDesk -Connection $conn -Table Tickets -Where "Status = '2'" | Select -Property * -ExcludeProperty Connection,Table,Columns | Export-Csv -Path c:\myTicketsData.csv -NoTypeInformation
Select-FreshDesk からの結果をSelect-Object cmdlet にパイプして、Export-CSV cmdlet にパイプする前にいくつかのプロパティを実行していることがわかるでしょう。これをする理由は、CData Cmdlets は接続、テーブル、およびカラムの情報を結果セットの各行オブジェクトに追加しますが、必ずしもその情報がCSV ファイルに必要ではないからです。
ただし、これによってcmdlet の出力を別のcmdlet にパイプすることが容易になります。以下に、結果セットをJSON に変換する例を示します。
PS C:\> $conn = Connect-FreshDesk -Domain "MyDomain" -APIKey "myAPIKey"
PS C:\> $row = Select-FreshDesk -Connection $conn -Table "Tickets" -Columns (Id, Name) -Where "Status = '2'" | select -first 1
PS C:\> $row | ConvertTo-Json
{
"Connection": {
},
"Table": "Tickets",
"Columns": [
],
"Id": "MyId",
"Name": "MyName"
}
データの削除
以下は、抽出条件に合うあらゆるレコードを削除します。
Select-FreshDesk -Connection $conn -Table Tickets -Where "Status = '2'" | Remove-FreshDesk
データの変更
cmdlet はデータクレンジング同様、データの変換を容易にします。次の例は、レコードがすでに存在するかどうか、挿入する前に更新が必要かどうかをチェックしてから、CSV ファイルのデータをFreshdesk にロードします。
Import-Csv -Path C:\MyTicketsUpdates.csv | %{
$record = Select-FreshDesk -Connection $conn -Table Tickets -Where ("Id = `'"+$_.Id+"`'")
if($record){
Update-FreshDesk -Connection $conn -Table Tickets -Columns @("Id","Name") -Values @($_.Id, $_.Name) -Where "Id = `'$_.Id`'"
}else{
Add-FreshDesk -Connection $conn -Table Tickets -Columns @("Id","Name") -Values @($_.Id, $_.Name)
}
}