在powershell脚本中将路径传递给SqlCmd [英] passing path to SqlCmd within powershell script
问题描述
我正在尝试编写一个 powershell 脚本,该脚本将执行 sqlcmd.exe 以运行 sql 脚本.该脚本包含一个 SQLCMD 变量,我想通过 sqlcmd 的 -v 开关在命令行上传递该变量.问题是,当我传递一个路径作为我的一个变量的值时,powershell 正在做一些奇怪的事情,这反过来导致 SQL 脚本失败.
I'm trying to write a powershell script which will execute sqlcmd.exe to run a sql script. The script contains a SQLCMD variable which I want to pass in on the command line via sqlcmd's -v switch. The problem is that powershell is doing something weird when I pass a path as the value of one of my variables which in turn causes the SQL script to fail.
例如我打电话:
$path = 'C:\path'
sqlcmd -SMySQLServerInstance -i 'MySqlScript.sql' -v MyVariablePath=$path
运行时我收到一条错误消息:
when run I receive a error which says:
Sqlcmd: ':\path': Invalid argument.
我在 $path
或 MyVariablePath=$path
周围没有尝试过多少双引号或单引号解决问题.
No amount of double or single quotes that I have tried around $path
or MyVariablePath=$path
solves the issue.
有人可以提供一个简单的规范示例来说明需要如何完成吗?
Can somebody provide a simple canonical example of how this needs to be done?
推荐答案
终于解决了.对于下一个尝试这个的傻瓜,这里是解决方案
finally worked it out. for the next sucker to try this here is the solution
powershell 脚本看起来像
powershell script looks like
$myPath = "`"C:\Path`""
sqlcmd.exe -SmySQLInstance -i./test.sql -v myvar=$myPath
我的 test.sql 文件可以像这样使用变量
my test.sql file can then use the variable like this
PRINT "$(myvar)"
这里的关键是了解 powershell 如何转义字符.关于更多信息这里
the key here is understanding how powershell does escape characters. More info on that here
这篇关于在powershell脚本中将路径传递给SqlCmd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!