PowerShell から Kusto .NET クライアント ライブラリを使用する

PowerShell スクリプトは Kusto クライアント ライブラリを使用できます。PowerShell は本質的に .NET ライブラリと統合されています。 この記事では、クライアント ライブラリを読み込んで使用してクエリと管理コマンドを実行する方法について説明します。

前提条件

  • 7-Zip や WinRAR などの zip ファイルを抽出するためのアーカイブ ツール。

ライブラリを取得する

PowerShell で Kusto .NET クライアント ライブラリを使用するには:

  1. Microsoft.Azure.Kusto.Tools をダウンロードします。

  2. ダウンロードしたパッケージを右クリックします。 メニューからアーカイブ ツールを選択し、パッケージの内容を抽出します。 アーカイブ ツールがメニューから表示されない場合は、[ その他のオプションを表示する] を選択します。 抽出の結果、複数のフォルダーが作成され、そのうちの 1 つは ツールという名前になります。

  3. tools フォルダー内には、異なる PowerShell バージョンに対応する異なるサブフォルダーがあります。 PowerShell バージョン 5.1 の場合は、 net472 フォルダーを使用します。 PowerShell バージョン 7 以降の場合は、いずれかのバージョン フォルダーを使用します。 関連するフォルダーのパスをコピーします。

  4. PowerShell からライブラリを読み込み、 をコピーしたフォルダー パスに置き換えます <path>

    [System.Reflection.Assembly]::LoadFrom("<path>\Kusto.Data.dll")
    

    次のような出力が表示されます。

    GAC (GAC) Version Location
    False v4.0.30319 C:\Downloads\tools\net472\Kusto.Data.dll

読み込まれたら、ライブラリを使用して クラスターとデータベースに接続できます。

クラスターとデータベースに接続する

次のいずれかの方法でクラスターとデータベースに対して認証を行います。

  • ユーザー認証: Web ブラウザーで ID を確認するようにユーザーに求めるメッセージを表示します。
  • アプリケーション認証:MS Entra アプリを作成し、認証に資格情報を使用します。
  • Azure CLI 認証: マシンで Azure CLI にサインインすると、Kusto は Azure CLI からトークンを取得します。

関連するタブを選択します。

最初のクエリまたはコマンドを実行すると、このメソッドによって、ユーザー承認用の対話型ブラウザー ウィンドウが開きます。

$clusterUrl = "<Your cluster URI>"
$databaseName = "<Your database name>"

$kcsb = New-Object Kusto.Data.KustoConnectionStringBuilder($clusterUrl, $databaseName)

クエリの実行

クエリ プロバイダーを作成し、クエリKusto 照会言語実行します。

次の例では、データをサンプリングする単純な take クエリを定義します。 クエリを実行するには、 をデータベース内のテーブルの名前に置き換えます <TableName> 。 クエリを実行する前に、 ClientRequestProperties クラス を使用して、クライアント要求 ID とサーバー タイムアウトを設定します。 次に、クエリが実行され、結果セットが書式設定されて並べ替えられます。

$queryProvider = [Kusto.Data.Net.Client.KustoClientFactory]::CreateCslQueryProvider($kcsb)
$query = "<TableName> | take 5"
Write-Host "Executing query: '$query' with connection string: '$($kcsb.ToString())'"

# Optional: set a client request ID and set a client request property (e.g. Server Timeout)
$crp = New-Object Kusto.Data.Common.ClientRequestProperties
$crp.ClientRequestId = "MyPowershellScript.ExecuteQuery." + [Guid]::NewGuid().ToString()
$crp.SetOption([Kusto.Data.Common.ClientRequestProperties]::OptionServerTimeout, [TimeSpan]::FromSeconds(30))

# Run the query
$reader = $queryProvider.ExecuteQuery($query, $crp)

# Do something with the result datatable
# For example: print it formatted as a table, sorted by the "StartTime" column in descending order
$dataTable = [Kusto.Cloud.Platform.Data.ExtendedDataReader]::ToDataSet($reader).Tables[0]
$dataView = New-Object System.Data.DataView($dataTable)
$dataView | Sort StartTime -Descending | Format-Table -AutoSize

出力

StartTime EndTime EpisodeID EventID EventType InjuriesDirect InjuriesIndirect DeathsDirect DeathsIndirect
2007-12-30 16:00:00 2007-12-30 16:05:00 11749 64588 GEORGIA 雷雨風 0 0 0 0
2007-12-20 07:50:00 2007-12-20 07:53:00 12554 68796 MISSISSIPPI 雷雨風 0 0 0 0
2007-09-29 08:11:00 2007-09-29 08:11:00 11091 61032 ATLANTIC SOUTH ウォーター スパウト 0 0 0 0
2007-09-20 21:57:00 2007-09-20 22:05:00 11078 60913 FLORIDA Tornado 0 0 0 0
2007-09-18 20:00:00 2007-09-19 18:00:00 11074 60904 FLORIDA Heavy Rain 0 0 0 0

管理コマンドを実行する

CSL 管理プロバイダーを作成し、 管理コマンドを実行します。

次の例では、管理コマンドを実行してクラスターの正常性をチェックします。

$adminProvider = [Kusto.Data.Net.Client.KustoClientFactory]::CreateCslAdminProvider($kcsb)
$command = [Kusto.Data.Common.CslCommandGenerator]::GenerateDiagnosticsShowCommand()
Write-Host "Executing command: '$command' with connection string: '$($kcsb.ToString())'"
# Run the command
$reader = $adminProvider.ExecuteControlCommand($command)
# Read the results
$reader.Read() # this reads a single row/record. If you have multiple ones returned, you can read in a loop
$isHealthy = $Reader.GetBoolean(0)
Write-Host "IsHealthy = $isHealthy"

出力

IsHealthy = True

Kusto クライアント ライブラリで管理コマンドを実行する方法の詳細については、「 管理コマンドを実行するアプリを作成する」を参照してください。

次の例では、ライブラリを読み込み、認証し、パブリックにアクセス可能 help なクラスターでクエリを実行するプロセスを示します。

#  This is an example of the location from where you extract the Microsoft.Azure.Kusto.Tools package
#  Make sure you load the types from a local directory and not from a remote share
#  Make sure you load the version compatible with your PowerShell version (see explanations above)
#  Use `dir "$packagesRoot\*" | Unblock-File` to make sure all these files can be loaded and executed
$packagesRoot = "C:\Microsoft.Azure.Kusto.Tools\tools\net472"
#  Load the Kusto client library and its dependencies
[System.Reflection.Assembly]::LoadFrom("$packagesRoot\Kusto.Data.dll")
#  Define the connection to the help cluster and database
$clusterUrl = "https://help.kusto.windows.net;Fed=True"
$databaseName = "Samples"
# MS Entra user authentication with interactive prompt
$kcsb = New-Object Kusto.Data.KustoConnectionStringBuilder($clusterUrl, $databaseName)
# Run a simple query
$queryProvider = [Kusto.Data.Net.Client.KustoClientFactory]::CreateCslQueryProvider($kcsb)
$query = "StormEvents | take 5"
$reader = $queryProvider.ExecuteQuery($query, $crp)