3

I am trying to to run mysql with input from a file. I have found that the following works:

cmd /c 'C:\Program Files\MySQL...\mysql -u user -pPassword databasename -f < inputfilename.sql'

The problem is that the databasename ($database) and inputfilename.sql ($file) are variables and need to be interpolated. I have not found any way to make the interpolation work.

Note that invoke-expression and & will not work because PowerShell doesn't implement < for input redirection.

Any suggestions?

user810702
  • 73
  • 1
  • 4

3 Answers3

1

I had exactly the same need as yours. Taking example from other SO answers like this one, here's what I wrote:

$binPath = <local MySQL bin path>
$mySql = Join-Path $binPath "mysql"
...
$dosCommand = "$mySql --host=$dbHost --user=$dbUser --password=$dbPassword $dbName --verbose < ""$scriptPath"""
cmd.exe /c $dosCommand
Community
  • 1
  • 1
superjos
  • 12,189
  • 6
  • 89
  • 134
  • Actually I'm fixing my code now and adding double quotes, from `... < $scriptPath"` to `... < ""$scriptPath"""`, otherwise I get errors when script path contains spaces. – superjos Mar 11 '14 at 18:08
0

You might be able to use Get-Content as answered in this similar question Why is "<" input redirect not implemented in Powershell?

Community
  • 1
  • 1
Chad Miller
  • 40,127
  • 3
  • 30
  • 34
-1

It looks like you're enclosing the entire command in single quotes. Variables don't get interpolated in single-quoted strings. Try this:

cmd /c 'C:\Program Files\MySQL\mysql' -u user -pPassword $database -f < $file
Aaron Jensen
  • 25,861
  • 15
  • 82
  • 91