Matías Fidemraizer Matías Fidemraizer - 1 year ago 74
SQL Question

Cannot run a database restore on Powershell because of < character

I'm trying to run the following command:

&$parameterHash["mysql"] -u $parameterHash["user"] -p"$($parameterHash['password'])" -h $parameterHash["host"] $parameterHash['database'] `< $parameterHash['backup-path']

Pay attention to this part of the whole command:

$parameterHash['database'] `< $parameterHash['backup-path']

This is the syntax of
command-line to restore a backup (i.e. a SQL script) from a file system location to a given database by its name.

First of all, I had to escape
in Powershell with a backtick.

The issue is that the entire command isn't recognized by
command line when I run it from Powershell. Once I run it,
outputs the help.

If I output the command as a string and I try to run it in regular
) it works as expected.

For now, I can't figure out what's going on.


I've also tried this:

$restoreArgs = "-u $($parameterHash["user"]) -p""$($parameterHash['password'])"" -h $($parameterHash["host"]) $($parameterHash['database']) < $($parameterHash['backup-path'])"
Start-Process $parameterHash["mysql"] $restoreArgs

...and I got the same result.

Answer Source

PowerShell doesn't support input redirection, only output redirection. I don't have MySQL at hand right now, so I can't test, but you could try

Get-Content $parameterHash['backup-path'] | &$parameterHash["mysql"] -u $parameterHash["user"] -p"$($parameterHash['password'])" -h $parameterHash["host"] $parameterHash['database']

If the input must be a single string call Get-Content with the parameter -Raw (PowerShell v3 and newer):

Get-Content $parameterHash['backup-path'] -Raw | ...

or pipe the Get-Content output through Out-String first:

Get-Content $parameterHash['backup-path'] | Out-String | ...

Another option is to run the commandline with CMD, which does support input redirection:

$mysql  = $parameterHash["mysql"]
$user   = $parameterHash["user"]
$pass   = $parameterHash['password']
$server = $parameterHash["host"]
$db     = $parameterHash['database']
$backup = $parameterHash['backup-path']

cmd /c "$mysql -u $username -p $password -h $server -d $db < $backup"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download