I just started experimenting with PowerShell for a project I’m doing. I haven’t seen any good examples on the web for how to run a PowerShell script generically from a batch file, so I’m sharing this framework.
First of all, before you run PowerShell scripts, you must change the security settings so that they will run. You can do this in PowerShell itself:
C:\>powershell PS C:\> Get-ExecutionPolicy Restricted PS C:\> Set-ExecutionPolicy RemoteSigned
After you have affected the security change, you can start using PowerShell. Next, write a batch file to execute your script:
:: psscript.bat set psscript='C:\psscript.ps1' echo Running PowerShell Script: %psscript% %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe ^&%psscript% %* set psscript=
A couple of comments on the batch file:
Notice that the path to psscript.ps1 is in single quotes.
I am executing the script by passing an odd array of characters to powershell.exe. The carat is an escape character for .bat files which tells windows not to process the “&” as if it were part of the command line. Therefore, the batch file passes & directly to powershell. In addition, I’m telling the batch file to pass all batch arguments by using %* (older versions of dos and maybe windows have used %1- to pass all arguments, but that definitely does not work on my testbed using Windows 2008 R2). On the command prompt, the command would look like this:
powershell.exe &'path-to-ps1.ps1' arg1 arg2
And here is the code for my first PowerShell script. It is designed to take a directory path as the argument from the command line and output a list of files and directories sorted in order of size from largest to smallest.
Here is the first PowerShell script. It’s really simple, and makes use of piping.
# psscript.ps1 Get-ChildItem $args | Sort-Object Length
To execute the code, run the batch file and pass in an argument like so:
You should get a listing of your files and directories in C:\ ordered by size. Enjoy!