This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

PowerShell

1 - Kusto .NET Client Libraries from PowerShell

This article describes how to use Kusto .NET Client Libraries from PowerShell.

PowerShell scripts can use the Kusto client libraries, as PowerShell inherently integrates with .NET libraries. In this article, you learn how to load and use the client libraries to run queries and management commands.

Prerequisites

  • An archiving tool to extract ZIP files, such as 7-Zip or WinRAR.

Get the libraries

To use the Kusto .NET client libraries in PowerShell:

  1. Download Microsoft.Azure.Kusto.Tools.

  2. Right-click on the downloaded package. From the menu, select your archiving tool and extract the package contents. If the archiving tool isn’t visible from the menu, select Show more options. The extraction results in multiple folders, one of which is named tools.

  3. Inside the tools folder, there are different subfolders catering to different PowerShell versions. For PowerShell version 5.1, use the net472 folder. For PowerShell version 7 or later, use any of the version folders. Copy the path of the relevant folder.

    You should see an output similar to the following:

    GACVersionLocation
    Falsev4.0.30319C:\Downloads\tools\net472\Kusto.Data.dll

Once loaded, you can use the libraries to connect to a cluster and database.

Connect to a cluster and database

Authenticate to a cluster and database with one of the following methods:

  • User authentication: Prompt the user to verify their identity in a web browser.
  • Application authentication: Create a Microsoft Entra app and use the credentials for authentication.
  • Azure CLI authentication: Sign-in to the Azure CLI on your machine, and Kusto will retrieve the token from Azure CLI.

Select the relevant tab.

User

Once you run your first query or command, this method opens an interactive browser window for user authorization.


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

Application

Create an MS Entra app and grant it access to your database. Then, provide the app credentials in place of the $applicationId, $applicationKey, and $authority.


$kcsb = New-Object Kusto.Data.KustoConnectionStringBuilder($clusterUrl, $databaseName)
$kcsb = $kcsb.WithAadApplicationKeyAuthentication($applicationId, $applicationKey, $authority)

Azure CLI

For this method of authentication to work, first sign-in to Azure CLI with the az login command.


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

Run a query

Create a query provider and run Kusto Query Language queries.

$queryProvider = [Kusto.Data.Net.Client.KustoClientFactory]::CreateCslQueryProvider($kcsb)
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

Output

StartTimeEndTimeEpisodeIDEventIDStateEventTypeInjuriesDirectInjuriesIndirectDeathsDirectDeathsIndirect
2007-12-30 16:00:002007-12-30 16:05:001174964588GEORGIAThunderstorm Wind0000
2007-12-20 07:50:002007-12-20 07:53:001255468796MISSISSIPPIThunderstorm Wind0000
2007-09-29 08:11:002007-09-29 08:11:001109161032ATLANTIC SOUTHWater spout0000
2007-09-20 21:57:002007-09-20 22:05:001107860913FLORIDATornado0000
2007-09-18 20:00:002007-09-19 18:00:001107460904FLORIDAHeavy Rain0000

Run a management command

Create a CSL admin provider and run management commands.

The following example runs a management command to check the health of the cluster.

$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"

Output

IsHealthy = True

For more information on how to run management commands with the Kusto client libraries, see Create an app to run management commands.

Example

The following example demonstrates the process of loading the libraries, authenticating, and executing a query on the publicly accessible help cluster.

#  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)

Controlling tracing

Since there’s only one global PowerShell.exe.config file for all PowerShell applications, generally libraries can’t rely on .NET’s app.config model to access their settings. You can still use the programmatic model for tracing. For more information, see controlling tracing.

You can use the following methods instead:

  • Enable tracing to the console:

    $traceListener = New-Object Kusto.Cloud.Platform.Utils.ConsoleTraceListener
    [Kusto.Cloud.Platform.Utils.TraceSourceManager]::RegisterTraceListener($traceListener)
    
  • Create a Kusto.Cloud.Platform.Utils.RollingCsvTraceListener2 object with a single argument of the folder location where traces are written.