sqlcmd/Invoke-SqlCmd 中的转义变量 [英] Escape variable in sqlcmd / Invoke-SqlCmd

查看:90
本文介绍了sqlcmd/Invoke-SqlCmd 中的转义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 powershell 并使用 Invoke-SqlCmd.我能够将变量传递给 SQL:

I am using powershell and using Invoke-SqlCmd. I am able to pass variables to SQL:

$variables = @( "MyVariable='hello'" )

Invoke-SqlCmd `
    -ServerInstance 'localhost' `
    -Database 'master' `
    -Username 'matthew' `
    -Password 'qwerty' `
    -Query 'SELECT $(MyVariable) AS foo' `
    -Variable $variables

这让我按预期返回hello.但是,如果我有一个包含等于 (=) 的值的变量:

This gives me back hello as expected. However, if I have a variable with a value containing an equals (=):

$variables = @("MyVariable='aGVsbG8NCg=='") # base64 encoded 'hello'

它给了我以下错误:

用于为 Invoke-Sqlcmd cmdlet 定义新变量的格式无效.请使用var=value"格式来定义新变量.

The format used to define the new variable for Invoke-Sqlcmd cmdlet is invalid. Please use the 'var=value' format for defining a new variable.

我找不到关于 sqlcmdInvoke-SqlCmd 的任何关于如何正确转义值的文档.

I could not find any documentation on either sqlcmd or Invoke-SqlCmd on how I should escape values properly.

如何转义发送到 sqlcmd/Invoke-SqlCmd 的变量?

How do I escape variables sent to sqlcmd / Invoke-SqlCmd?

推荐答案

在调查之后使用了一些反思

After investigating using some reflection on

C:\Program Files (x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\SQLPS\Microsoft.SqlServer.Management.PSSnapins.dll

C:\Program Files (x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\SQLPS\Microsoft.SqlServer.Management.PSSnapins.dll

查看ExecutionProcessor的构造函数,下面几行揭示了如果变量定义中有多个等号它会失败的问题.

Looking at ExecutionProcessor's constructor, the following lines reveal the problem that it will fail if there are more than one equals sign in the variable definition.

我对尝试使用 Invoke-SqlCmd 的其他人的建议是节省您的时间和理智,并且只使用开源替代方案 Invoke-SqlCmd2 代替.

My recommendation for anyone else trying to use Invoke-SqlCmd is to save your time and sanity and just use the open source alternative Invoke-SqlCmd2 instead.

微软,请修复.

这篇关于sqlcmd/Invoke-SqlCmd 中的转义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆