Writing Powershell command (.ps1) files

In a previous post I started to look into using Powershell, but ofcourse the power of commands/Cmdlets comes when they’re either combined or whereby our most common commands exist in files to be run again and again.

So let’s turn an often used command into a ps1 file.

Windows PowerShell ISE (Integrated Scripting Engine)

From the Windows search box (ctrl+R) we can run up the Windows PowerShell ISE. This gives us, both an editor and also a command prompt for writing and testing our command scripts.

You can also run this application from the command line using powershell_is or better still via the alias ise.

In the editor let’s type

Get-Process | where {$_.CPU -gt 1000}

Now save this file as Top-Cpu.ps1

Running our new command

We can simply drag and drop a ps1 file from Windows Explorer onto the Powershell window to fill in the fully qualified path on the command line, pressing enter we can then run the file. Obviously if you know the full path you can do this yourself by typing the same into the command prompt.

Specifying parameters

It may be that our ps1 file is perfect as it is, but it’s also quite likely we’ll want to allow the user to change some values in it at runtime, i.e. using command line arguments/parameters.

To specify parameters in our script we write

param(cpu=1000)

This defines a parameter named cpu and gives a default value, in this case 1000. If we change our script to look like this

param($cpu=1000)
Get-Process | where {$_.CPU -gt $cpu}

where you’ll notice $cpu is the placeholder/variable where the parameter is used. We can now run this script as Top-cpu.ps1 and the default parameter is used. Or we might write Top-cpu.ps1 7000 to supply a new parameter.

Multiple parameters

We can command separate our parameters to include multiple params, like this

param($value=1000, $field="CPU")
Get-Process | where {$_.$field -gt $value}

Maybe not so useful in this specific script, but you get the idea.

References

Windows PowerShell: Defining Parameters