powershell - 静默 Azure SQL Powershell 命令的输出

标签 powershell azure-sql-database

我有一个 Powershell 脚本,用于将我们的生产数据库复制到我们的测试环境以及相关的清理事件。我想清理为用户输出到控制台的信息,但在清理从 Az.sql 命令中收到的错误消息时遇到了问题。

我的第一个 Action 是尝试查看是否存在临时数据库并需要清理

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

如果它不存在,我将在控制台中得到以下错误输出:

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

我想捕获此输出并提供一个简单的“不存在”消息,或者甚至只是完全继续而没有任何输出。我试过将“| Out-Null”放在末尾,但这似乎不会以任何方式影响输出。有什么见解吗?

最佳答案

你只需要使用 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" 

    }

测试结果:

enter image description here

enter image description here

关于powershell - 静默 Azure SQL Powershell 命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58527453/

相关文章:

powershell - Windows 网络适配器禁用通过 Powershell 启用

regex - Powershell 通配符/正则表达式替换

asp.net - 动态数据掩码停止工作

c# - Entity Framework 6 中的 CreatedOn 列

azure - Azure 应用服务移动应用中 Easy Table 中的主键/外键

powershell - 相当于 Powershell 中的 `type -a`

bash - Bash 上的反勾号的 cmd/PowerShell 等价物是什么?

Powershell < 属性名称中的符号

sql-server - 无法加载文件或程序集 Microsoft.SqlServer.TransactSql

Azure 服务器实例限制和命名