在Azure runbook中调用Sqlcmd时是否应该使用PowerShell子表达式



我们使用Azure Automation powershell runbook进行Azure Sql维护,类似于中所述https://www.2azure.nl/2020/07/28/how-to-use-azure-automation-to-maintain-sql-indexes-and-statistics/(在Azure Automation Powersell Runbook中失败:';Invoke-Sqlcmd';未被识别为cmdlet应答的名称(

$SQLOutput = $(Invoke-Sqlcmd -ServerInstance $AzureSQLServerName 
-Username $Cred.UserName -Password $Cred.GetNetworkCredential().Password
-Database $AzureSQLDatabaseName -Query $sql 
-QueryTimeout 65535 -ConnectionTimeout 60 -Verbose) 4>&1
Write-Output $SQLOutput

但我们发现,如果出现错误(尤其是用户名错误(,即使错误记录在输出中,作业也会成功结束。这是否意味着子表达式$(command(静默地捕获异常?中未提及https://ss64.com/ps/syntax-operators.html.

将子表达式保存到$SQLOutput的另一个问题是,我们只能在$(Invoke-Sqlcmd(完成后才能看到输出,而不能在过程中看到。如果$(Invoke-Sqlcmd(花费了3个多小时,Azure就会停止作业,我们看不到处理了什么,没有处理什么。

是否应该完全不使用子表达式并直接调用Invoke-Sqlcmd?

Invoke-Sqlcmd -ServerInstance $AzureSQLServerName 
-Username $Cred.UserName -Password $Cred.GetNetworkCredential().Password 
-Database $AzureSQLDatabaseName -Query  $sql 
-QueryTimeout 65535 -ConnectionTimeout 60 -Verbose) 4>&1

与子表达式相比,它会有什么缺点吗?

为了在调用Sqlcmd期间报告错误,我添加了两个参数

-ErrorAction Stop   

从Powershell Try-Catch调用sqlcmd

-AbortOnError  

从Powershell的错误检测调用Sqlcmd不总是工作?

仍然没有确认,将子表达式保存到$SQLOutput 是否有任何好处

最新更新