Powershell sql 部署脚本无法使用环境变量

Powershell sql deploy script is not working with env variavle

我在 constants.groovy 文件中有以下行:

myMap = [
    "TEST":["SQL_URL":"Data Source=TEST,123", "credential":"" ]
]

jenkinsfile.groovy中的这一行:

bat "powershell.exe -file pipeline/powershell/deploy_sql.ps1 ${myMap[env.Environment_Type].SQL_URL}"

deploy_sql.ps1 中的这一行:

$Env = $args[0]
$msbuild = Start-Process -FilePath "msbuild" -ArgumentList '"Database Services\Database Services.sqlproj"','/t:deploy','/p:Configuration=Release','/p:TargetConnectionString="Data Source="+$Env+";Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"','/p:BlockOnPossibleDataLoss=True','/p:TargetDatabase="bnhp_fsdb"','-fl','-flp:logfile=msbuild.log' -wait -PassThru

但我在日志中收到此错误:

Deploy error Deploy72002: Unable to connect to target server '+$Env+'. Please verify the connection information such as the server name, login credentials, and firewall rules for the target server.

当我 运行 完整的硬编码数据源时,它可以工作,所以我猜 powershell 语法有问题

PowerShell 字符串文字有两种形式:verbatimexpandable.

逐字字符串文字用单引号括起来 ('),可扩展字符串用双引号括起来 (")。

将受影响的字符串文字转换为可扩展字符串需要我们:

  • 将周围的引号更改为 "
  • 通过加倍转义字符串中的所有文字"
  • 使用 `(反引号)
  • 转义任何剩余的特殊字符

对于您的情况,我们会更改:

'/p:TargetConnectionString="Data Source="+$Env+";Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"'

至:

"/p:TargetConnectionString=""Data Source=${Env};Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"""