Thursday, October 6, 2016

Moving data from PowerShell to a batch script

Sometimes getting a certain piece of data is dramatically easier in PowerShell than with the normal command-line utilities. If you've already written a script for batch, then it would be good to marshal data from PowerShell back into a batch variable.

That's moderately easy with PowerShell's Out-File and the command prompt's set /p. You do have to be careful with encoding: PowerShell by default spits out UTF-16LE files with a byte order mark, and set /p doesn't work well with that. The -Encoding switch has you covered.

This little fragment of batch scripting uses PowerShell to get the location of the user's Documents folder and stores it in a batch variable called DOCSPATH:

powershell -Command "[Environment]::GetFolderPath('MyDocuments') | Out-File 'docspath.tmp' -Encoding ascii"
set /p DOCSPATH=< docspath.tmp
del docspath.tmp

This only works well for data representable as text, but the command prompt doesn't really handle objects anyway, so that's OK. You do need write access to the current directory to run the above snippet; if that's an issue, change the file paths to point somewhere writable.

Based on my Super User answer.

No comments:

Post a Comment