【问题标题】:Should I use PowerShell subexpression when Invoke-Sqlcmd in Azure runbook?在 Azure Runbook 中调用 Sqlcmd 时是否应该使用 PowerShell 子表达式?
【发布时间】:2021-07-30 20:01:04
【问题描述】:

我们正在使用 Azure 自动化 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 fails: 'Invoke-Sqlcmd' is not recognized as the name of a 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

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

【问题讨论】:

  • 我会为此使用Splatting。它创建了可读性/可维护性好的代码。 (虽然无法测试提供错误用户名时会发生什么..)
  • @theo,感谢您参考 Splatting。我不知道。

标签: azure powershell azure-runbook invoke-sqlcmd


【解决方案1】:

为了在 Invoke-Sqlcmd 过程中报错,我添加了 2 个参数

 -ErrorAction Stop   

来自Powershell Try Catch invoke-sqlcmd

 -AbortOnError  

来自Error detection from Powershell Invoke-Sqlcmd not always working?

仍然没有确认,将子表达式保存到 $SQLOutput 有什么好处

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2019-03-24
    • 2019-03-20
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多