如何在PowerShell中运行以下命令?
C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe -verb:sync -source:dbfullsql="数据源=mysource;集成安全=false;用户ID=sa;Pwd=sapass!;数据库=mydb;"-dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"
这招对我很管用:
PowerShell.exe -Command "& ""C:\Some Script\Path With Spaces.ps1"""
关键似乎是整个命令都用外引号括起来,“&”&用于指定正在执行的另一个子命令文件,然后最后在路径/文件名周围转义(双-双-)引号,其中有空格。
这也是MS连接问题的唯一解决方案,即-File不传递非零返回码,而-Command是唯一的替代方案。但到目前为止,人们认为-Command的一个限制是它不支持空格。我也更新了反馈内容。
http://connect.microsoft.com/PowerShell/feedback/details/750653/powershell-exe-doesn-t-return-correct-exit-codes-when-using-the-file-option
我使用这种简单、干净、有效的方法。
我在数组中放置参数,每行1个。这样就很容易阅读和编辑了。
然后我使用一个简单的技巧,将所有参数都放在双引号内传递给一个只有一个形参的函数。这将它们(包括数组)压扁为一个字符串,然后我使用PS的“Invoke-Expression”执行。此指令专门用于将字符串转换为可运行命令。
适用:
# function with one argument will flatten
# all passed-in entries into 1 single string line
Function Execute($command) {
# execute:
Invoke-Expression $command;
# if you have trouble try:
# Invoke-Expression "& $command";
# or if you need also output to a variable
# Invoke-Expression $command | Tee-Object -Variable cmdOutput;
}
# ... your main code here ...
# The name of your executable app
$app = 'my_app.exe';
# List of arguments:
# Notice the type of quotes - important !
# Those in single quotes are normal strings, like 'Peter'
$args = 'arg1',
'arg2',
$some_variable,
'arg4',
"arg5='with quotes'",
'arg6',
"arg7 \ with \ $other_variable",
'etc...';
# pass all arguments inside double quotes
Execute "$app $args";
PowerShell V3中的新转义字符串,引用自New V3语言特性:
更容易重用Cmd.exe中的命令行
web上充满了为Cmd.exe编写的命令行。这些命令行在PowerShell中经常工作,但是当它们包含某些字符时,例如分号(;)、美元符号($)或花括号,您必须进行一些更改,可能会添加一些引号。这似乎是许多小头痛的根源。
为了帮助解决这种情况,我们添加了一种“转义”命令行的解析的新方法。如果您使用一个神奇的参数——%,我们将停止对命令行的正常解析,并切换到更简单的内容。我们不匹配报价。我们不会止步于分号。我们不展开PowerShell变量。如果您使用Cmd.exe语法(例如%TEMP%),我们会展开环境变量。除此之外,直到行(或管道,如果您使用管道)末端的参数都是原样传递的。这里有一个例子:
PS> echoargs.exe --% %USERNAME%,this=$something{weird}
Arg 0 is <jason,this=$something{weird}>