Creating a Function for PowerCLI

Ive been trying to clean up several scripts I’ve been using in the office in preparation for a large project im working on. Like so many, ive had issues come up, and I have built out a scripts to tackle it, each time. Sometimes I ended up rewriting repetitive items I had done before. One thing I started getting back into during clean up, is using reusable code, like a method in java for instance, in this case creating functions.

Below is a small example of Ill go into a few ways to make use of this function in a later entry, and ill make sure to link back here.

[code language=”powershell”]
#Simple function to add two numbers

#"function" followed by the name of the function "add-something","get-something" etc
Function Add-PrestonMPG {
#your parameters, ill make a list of more examples later
Param ([int]$x,[int]$y)

$z = $x + $y

Write-Output $z



To test it out, you can just copy and paste the code into powershell or paste and run it in powershell ISE. Once run, if you start typing “Add-Pre” in the console it will now be available. It will also show you the variable inputs.


Screenshot at Apr 27 02-40-16

A sample run of the function can be something like: Add-PrestonMPG -x 22 -y 33

Screenshot at Apr 27 02-40-44

Thats all there is to making your own basic functions.