Thursday, July 28, 2011

Using PowerShell to write and execute CMD and BAT

Here is the important part, right up front:  remember your encoding when using Out-File.

There, done.

No, seriously – this is one of those silly things that I just spent a while figuring out.

I have a PowerShell script and it is querying for variables for me.  I have an executable that I need to run and it will not call properly using PowerShell.  The answer; write your commands to a CMD file and then simply call it.

"@echo on" | out-File -filepath "$exPath\Thing.cmd"
        '"' + $ThingExe + '"' + ' config /user:"' + $AccountName + '" /pwd:"' + $Password + '" /dsn:"' + $exPath + '\sql.dsn"' | out-File -filepath "$exPath\Thing.cmd" -append -noclobber
        "net stop ThingService" | out-File -filepath "$exPath\Thing.cmd" -append -noclobber
        "net start ThingService" | out-File -filepath "$exPath\Thing.cmd" -append –noclobber

That is the PoSh to write the CMD file.  Great.  Now, execute it.

Immediately, an error:  ‘<box>@’ is not the name of a command

What?!?  Where is this <box> character coming from?  It is coming from Unicode.

Simply edit each and every Out-File with –encoding ASCII.  The first line will look like this:

"@echo on" | out-File -encoding ASCII -filepath "$exPath\Thing.cmd"

Remember, you need to add the encoding to all Out-File commands that affect the file.  If you don’t, the files that have it missing will end up looking like “@  e c h o  o n” and the lines with the encoding set to ASCII will look like “@echo on”.

And then to execute the CMD just add the line to your script: 

& $exPath\Thing.cmd

PS – for me the $exPath is the current path where the script is executing.  You can get this with:

$exPath = Split-Path -parent $MyInvocation.MyCommand.Definition

No comments: