More CLI and PowerShell

You don’t have to choose between the traditional command line interface (CLI) and PowerShell.  You can easily run a PowerShell command or even a PowerShell script directly from a command prompt. This means you can integrate some PowerShell functionality into your older batch files. It also means that you can create a scheduled task to execute a PowerShell script!

At a command prompt, run powershell /? and you’ll see the proper syntax.  Generally, you will want to use the format powershell -command “&{some powershell expression}”.  I also prefer to use -nologo to suppress the Windows PowerShell logo. This is especially useful if you want to capture the ouput to a text file. This also brings up an important point, because you are calling PowerShell from the CLI, any output returned is text and not a PowerShell object. So when you run a CLI command like this:

powershell -nologo -command “& {get-process}”

It looks like normal PowerShell output.  But if you capture it, it’s just text. Not that this is a bad thing. It may be just want you want.

I’ve put together a little batch file demo that you can run. It saves the output from several PowerShell expressions to a text file. It can even run a .ps1 file.

@echo off
REM PoSHTest.bat
set zlog=e:\temp\pslog.txt
echo %date% %time% > %zlog%
powershell -nologo -command “& {get-wmiobject win32_operatingsystem}” >>%zlog%
REM you can use aliases
powershell -nologo -command “& {gwmi win32_computersystem}” >>%zlog%
REM You can use filtering blocks
powershell -nologo -command “& {get-service | where {$_.status -eq ‘running’}}” >>%zlog%
REM You can call other PowerShell scripts
powershell -nologo -command “& {s:\posh\scheduleTest.ps1}”

echo See %zlog% for results
set zlog=

If you want to try this out be sure to change the zlog variable path and any PowerShell script you might want to run. You should test this first interactively. Assuming everything works, then try it out as a scheduled task on your system.  You should have an appropriate log file after the job completes.

If you try to schedule a batch file to run a PowerShell script, make sure the ps1 script doesn’t require any user input or interaction. Unless, of course, you create the job to be interactive.

Once you get the hang of it, you’ll realize you don’t always have to launch a full PowerShell instance to get something done. If you need the results of a simple PowerShell expression, you can stay in the CLI and get the best of both worlds.