当PowerShell看到以字符串开头的命令时,它只计算字符串,也就是说,它通常会将其回显到屏幕上,例如:
PS> "Hello World"
Hello World
如果你想让PowerShell将字符串解释为命令名,那么使用调用操作符(&),如下所示:
PS> & 'C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe'
After that you probably only need to quote parameter/argument pairs that contain spaces and/or quotation chars. When you invoke an EXE file like this with complex command line arguments it is usually very helpful to have a tool that will show you how PowerShell sends the arguments to the EXE file. The PowerShell Community Extensions has such a tool. It is called echoargs. You just replace the EXE file with echoargs - leaving all the arguments in place, and it will show you how the EXE file will receive the arguments, for example:
PS> echoargs -verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=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
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data>
Arg 2 is <Source=mysource;Integrated>
Arg 3 is <Security=false;User>
Arg 4 is <ID=sa;Pwd=sapass!;Database=mydb;>
Arg 5 is <-dest:dbfullsql=Data>
Arg 6 is <Source=.\mydestsource;Integrated>
Arg 7 is <Security=false;User>
Arg 8 is <ID=sa;Pwd=sapass!;Database=mydb; computername=10.10.10.10 username=administrator password=adminpass>
使用回声,你可以不断实验,直到你得到正确的答案,例如:
PS> echoargs -verb:sync "-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;"
Arg 0 is <-verb:sync>
Arg 1 is <-source:dbfullsql=Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;>
事实证明,我以前在连接字符串周围保持双引号时太过努力了。显然,这是不必要的,因为即使cmd.exe也会删除这些文件。
顺便说一句,向PowerShell团队致敬。他们在向我展示单引号和双引号的具体咒语以获得所需的结果方面非常有帮助-如果你需要保持内部双引号到位。:-)他们也意识到这是一个痛苦的领域,但他们是由受特定问题影响的人数所驱动的。如果这对你来说是一个痛苦的领域,那么请为这个PowerShell错误提交投票。
有关PowerShell如何解析的更多信息,请查看我的Effective PowerShell博客系列——特别是第10项——“理解PowerShell解析模式”
2012年4月4日更新:这种情况在PowerShell V3中更容易处理。详见这篇博客文章。