共用方式為


使用 PowerShell 進階搜尋

適用於:

想要體驗適用於端點的 Microsoft Defender 嗎? 注册免費試用版。

注意事項

如果您是美國政府客戶,請使用美國政府客戶 適用於端點的 Microsoft Defender 中所列的 URI。

提示

為了獲得更好的效能,您可以使用更接近您地理位置的伺服器:

  • us.api.security.microsoft.com
  • eu.api.security.microsoft.com
  • uk.api.security.microsoft.com
  • au.api.security.microsoft.com
  • swa.api.security.microsoft.com

使用 PowerShell 執行進階查詢。 如需詳細資訊,請參閱 進階搜捕 API

在本節中,我們會共用 PowerShell 範例來擷取令牌,並使用它來執行查詢。

開始之前

您必須先 建立應用程式

準備指示

  • 開啟 PowerShell 視窗。

  • 如果您的原則不允許您執行 PowerShell 命令,您可以執行下列命令:

    Set-ExecutionPolicy -ExecutionPolicy Bypass
    

如需詳細資訊,請參閱 PowerShell檔

取得令牌

  • 執行下列命令:
$tenantId = '00000000-0000-0000-0000-000000000000' # Paste your own tenant ID here
$appId = '11111111-1111-1111-1111-111111111111' # Paste your own app ID here
$appSecret = '22222222-2222-2222-2222-222222222222' # Paste your own app secret here

$resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
$oAuthUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$body = [Ordered] @{
    resource = "$resourceAppIdUri"
    client_id = "$appId"
    client_secret = "$appSecret"
    grant_type = 'client_credentials'
}
$response = Invoke-RestMethod -Method Post -Uri $oAuthUri -Body $body -ErrorAction Stop
$aadToken = $response.access_token

其中

  • $tenantId:代表您要執行查詢的租使用者標識碼 (也就是說,查詢會在此租用戶的數據上執行)
  • $appId:Microsoft Entra 應用程式的標識符, (應用程式必須具有適用於端點的Defender的「執行進階查詢」許可權)
  • $appSecret:Microsoft Entra 應用程式的秘密

執行查詢

執行下列查詢:

$token = $aadToken
$query = 'DeviceRegistryEvents | limit 10' # Paste your own query here

$url = "https://api.securitycenter.microsoft.com/api/advancedqueries/run"
$headers = @{ 
    'Content-Type' = 'application/json'
    Accept = 'application/json'
    Authorization = "Bearer $aadToken" 
}
$body = ConvertTo-Json -InputObject @{ 'Query' = $query }
$webResponse = Invoke-WebRequest -Method Post -Uri $url -Headers $headers -Body $body -ErrorAction Stop
$response =  $webResponse | ConvertFrom-Json
$results = $response.Results
$schema = $response.Schema
  • $results包含查詢的結果
  • $schema包含查詢結果的架構

複雜查詢

如果您想要) 執行複雜的查詢 (或多行查詢,請將查詢儲存在檔案中,而不是上述範例中的第一行,請執行下列命令:

$query = [IO.File]::ReadAllText("C:\myQuery.txt"); # Replace with the path to your file

使用查詢結果工作

您現在可以使用查詢結果。

若要以檔案 file1.csv 格式輸出 CSV 格式的查詢結果,請執行下列命令:

$results | ConvertTo-Csv -NoTypeInformation | Set-Content C:\file1.csv

若要以檔案file1.json格式輸出 JSON 格式的查詢結果,請執行下列命令:

$results | ConvertTo-Json | Set-Content file1.json

相關文章

提示

想要深入了解? Engage 技術社群中的 Microsoft 安全性社群:適用於端點的 Microsoft Defender 技術社群。