WebClient DownloadFile problem

I’m new to powershell but I think I’m trying to do something pretty simple. I probably just have a syntax error!

I’ve written this command:

(New-Object System.Net.WebClient).DownloadFile("http://MySite/fileextract.asp?userid=MyUser`&password=MyPassword`&file=MyFile.zip","c:\Download\MyFile.zip")

Which runs successfully in Powershell.

The problem I’m having is that when I try to use to Powershell.exe -command syntax in a batch file, I keep getting an error:

PowerShell.exe -Command {(New-Object System.Net.WebClient).DownloadFile("http://MySite/fileextract.asp?userid=MyUser`&password=MyPassword`&file=MyFile.zip","c:\Download\MyFile.zip")}

I get an unexpected token error on the coma character. Notice that there is two & characters in the url that I had to escape with `.

What I’m I doing wrong?


powershell.exe has the -EncodedCommand parameter specifically to help you deal with weird parsing issues like this. You just need to convert your command to a base64 string (examples for this are in powershell.exe /?). For example:

$code = @'
(New-Object System.Net.WebClient).DownloadFile("http://MySite/fileextract.asp?userid=MyUser`&password=MyPassword`&file=MyFile.zip","c:\Download\MyFile.zip")

$unicodeBytes = [System.Text.Encoding]::Unicode.GetBytes($code)
$base64 = [System.Convert]::ToBase64String($unicodeBytes)
Set-Clipboard $base64

If you run that code, it puts the base64 representation of your command in the clipboard (assuming you’re running a version of PowerShell with the Set-Clipboard command, of course.) Then you just need to call powershell.exe like this:


Great, this works perfectly!

Thanks alot!