Running Powershell script functions


Many of the scripts I write contain reusable code as functions. For example, the Merge-VMDisks.PS1 script contains Merge-VMDisks function. To use these functions, you must load them first into memory in the current Powershell session. Running the PS1 file will do just that; load the function in memory. It will NOT run the function.

Powershell stores a list of the currently available functions in the function: drive. To see available drives type:

Get-PSDrive

You will get a result similar to:

Function1To explore the contents of a PS drive, we can use the Get-Item cmdlet like:

Get-Item -Path function:

You will get a result similar to:

Function2In this example, to use the Merge-VMDisks function we need to load it into memory first in the current PS session by running the PS1 file:

E:\Install\Scripts\Merge-VMDisks.ps1
Get-Item -Path function:

Now running the Get-Item cmdlet shows 3 new functions loaded – that we got form the Merge-VMDisks.ps1 script:

Function3

Now that we have the function in memory, we can use it by invoking the function as we do any PS cmdlet. For example:

Merge-VMDisks -VMName ‘MyVM’

 

 

 

Advertisements

2 responses

  1. Jürgen

    Great Artikel.

    Thanks, this articel helps me a lot understanding functions!

    March 28, 2015 at 9:32 am

  2. to load the function need . .\mergevmdisks.ps1 (dot space dot)

    December 6, 2016 at 6:52 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s