防止可变的变量和特殊字符替代
我使用存储过程将从文件从文件加载到数据库中,例如:
$stuff = Get-Content -Path '.\data.txt' -Raw
Invoke-Sqlcmd -Query "Exec dbo.loadStuff @stuff='$stuff'" -ServerInstance $server -Database $database -Username $username -Password $password
这大多数时间都可以,但是有时该文件包含$ tocalText
powerShell然后未能扩展,因为<<代码> $ RandomText 不存在变量。
有没有办法告诉PowerShell不扩展$ QUATE
变量的内容?
添加-disableVariobles
似乎不起作用。
编辑:正如Zett42指出的那样,PowerShell并没有执行第二次扩展。它将全文传递给sqlcmd
。
sqlcmd
正在查找$(RandomText)
并将其视为变量。 -disableVariobles
应该已经修复了此问题,但事实并非如此。
从测试源文件中删除了所有$符号后,它仍然失败,我怀疑它是由于$ QUATE
包含单个和双引号。
我还没有意识到Invoke-SQLCMD
只是传递到sqlcmd
。我将停止使用Indoke-SQLCMD
,并遵循Zett42提供的资源。
I'm loading a regex from a file into a database using a stored procedure, like this:
$stuff = Get-Content -Path '.\data.txt' -Raw
Invoke-Sqlcmd -Query "Exec dbo.loadStuff @stuff='$stuff'" -ServerInstance $server -Database $database -Username $username -Password $password
This works most of the time, but sometimes the file contains $randomtext
which PowerShell then fails to expand because the $randomtext
variable doesn't exist.
Is there a way to tell PowerShell to pass the contents of the $stuff
variable as is without expanding it?
Adding -DisableVariables
doesn't appear to work.
EDIT: As zett42 pointed out, PowerShell isn't performing a second expansion. It is passing the full text to sqlcmd
.
sqlcmd
is finding $(randomtext)
and treating it as a variable. -DisableVariables
should have fixed this, but it hasn't.
After removing all $ signs from the test source file it is still failing, and I suspect that it is due to $stuff
containing single and double quotes.
I hadn't realised that Invoke-Sqlcmd
is simply a pass through to sqlcmd
. I will stop using Invoke-Sqlcmd
and follow the resource provided by zett42 instead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Invoke-SQLCMD
非常适合简单调用,但是如果您要执行更复杂的事情(例如将任意文本作为参数传递),则最好使用.NET堆栈(例如system)。 data.sqlclient.sqlcommand
。我已经重写了我的代码以使用这种更合适的方法,并且我能够传递绑定的参数(不可能进行SQL注入)没有PowerShell或SQLCMD Mangling或试图解析参数值(这两种)是原始问题的原因)。
Invoke-Sqlcmd
is great for simple calls, but if you're going to do anything more complex (like pass arbitrary text as a parameter) it's best to use the .NET stack likeSystem.Data.SqlClient.SqlCommand
.I have rewritten my code to use this more appropriate approach and I am able to pass bound parameters (no possibility of SQL injection) without either PowerShell or sqlcmd mangling or trying to parse the parameter values (both of which were the cause of the original problems).