Wednesday, December 9, 2009

Windows Commands with Arguments in Powershell

I have been trying to write a simple PowerShell script that runs (invokes?) MySqlDump.exe for two days. PowerShell syntax for running commands with arguments is not obvious and I wasn't able to find it documented anywhere. While this case is specific to mysqldump, it can be applied to any command line executable with multiple arguments. The trick is to create an array of the arguments and use that as the second "argument" for the ampersand (&) call operator. Here's what my final example looked like:



[string]$pathToExe = "C:\MySQL\MySQL Server 5.1\bin\mysqldump.exe";
[string]$user = "myUser";
[string]$password = "myPass";
[string]$dbName = "myDB";
[Array]$arguments = "-u", $user, "--password=$password", $dbName;

& $pathToExe $arguments | Out-File -FileName "out.sql";




So there you have it. That's how to run an executable with spaces and arguments from PowerShell.

While this article from PowerShell.com didn't answer my questions, I thought it was pretty useful and relevent:

http://powershell.com/cs/blogs/ebook/archive/2009/03/30/chapter-12-command-discovery-and-scriptblocks.aspx

No comments: