簡體   English   中英

靜音 Output 來自 Azure SQL Z531B84AD41B2A7053DA83ACF371

[英]Silence Output From Azure SQL Powershell Commands

我有一個 Powershell 腳本將我們的生產數據庫復制到我們的測試環境以及相關的清理活動。 我想清理為用戶輸出到控制台的信息,但在清理我從 Az.sql 命令中得到的錯誤消息時遇到了麻煩。

我的第一個操作是嘗試查看是否存在臨時數據庫並且需要清理

#clean up existing
$availableDatabase = Get-AzSqlDatabase -ResourceGroupName $TestResourceGroup -ServerName $TestServerName -DatabaseName $TestTempDatabaseName

如果它不存在,我將在控制台中收到以下錯誤 output:

Remove-AzSqlDatabase : The Resource 
'Microsoft.Sql/servers/xxxx/databases/reap_prod_copy_2' under resource group 'xxxx' was not found.
At C:\Users\xxxx\Desktop\reap-replace-test.ps1:17 char:1
+ Remove-AzSqlDatabase -ResourceGroupName $TestResourceGroup -ServerNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : CloseError: (:) [Remove-AzSqlDatabase], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Sql.Database.Cmdlet.RemoveAzureSqlDatabase

我想捕獲這個 output 並提供一個簡單的“不存在”消息,或者甚至在沒有任何 output 的情況下完全繼續前進。 我試過把“| Out-Null”放在最后,但這似乎不會以任何方式影響 output。 有什么見解嗎?

您可以使用try catch塊來捕獲異常。

try {
    #clean up existing
    $availableDatabase = Get-AzSqlDatabase -ResourceGroupName $TestResourceGroup -ServerName $TestServerName -DatabaseName $TestTempDatabaseName
} 
catch {
    Write-Host "Does not exist"
    $availableDatabase = $null
}

if ($availableDatabase -ne $null) {
    # ... Do stuff with database
}

以上將執行try塊中的所有內容,如果遇到任何類型的錯誤,它將執行catch塊中的所有內容。 if語句可能需要也可能不需要,具體取決於實現。

about_Try_Catch_Finally

注意:上面的catch塊將捕獲任何錯誤,無論它是否是由丟失的表引起的。 通常最好的做法是在可能的情況下在catch之后包含特定的異常類型,以避免消除可能需要修復的不相關錯誤。

你只需要使用if(){}else{}語句來做到這一點,試試下面的腳本,它在我這邊運行良好。

$availableDatabase = Get-AzSqlDatabase -ResourceGroupName $TestResourceGroup -ServerName $TestServerName -DatabaseName $TestTempDatabaseName -ErrorAction SilentlyContinue
if ($availableDatabase){

    Remove-AzSqlDatabase -ResourceGroupName $TestResourceGroup -ServerName $TestServerName -DatabaseName $TestTempDatabaseName
    Write-Host "Remove the sql db" $TestTempDatabaseName

}else{
    Write-Host "The sql db" $TestTempDatabaseName "does not exist" 

    }

測試結果:

在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM