Learn to use a PowerShell call function from another script | TechTarget (2024)

No one wants to repeat themselves, and the same goes for PowerShell code.

A function is a group of commands with a function name that you use once or multiple times in a script to avoid duplicating code. After you gain enough PowerShell experience, you will eventually switch from basic variable use to functions for added flexibility. When you understand all the ways to call a function, you will move up to the next level of scripting that makes your functions easier to support and to reuse in multiple scripts.

How to call a function: The inline approach

The easiest way to work with a PowerShell function is to include it in the script. The term for this is an inline function. Wherever the code is for the function, it must go above the first line that calls the function. In most cases, inline functions reside in a group at the start of the script in their own dedicated region.

Example: Return the IPv4 address

The following example uses a simple function to display the IPv4 address of the user's system. The function contains the syntax for the Get-NetIPAddress cmdlet and includes the parameters to filter the output.

Function Get-IpAddress {
Get-NetIPAddress -AddressFamily IPv4 -AddressState Preferred | `
Where-Object { $_.PrefixOrigin -ne 'WellKnown' } | `
Select-Object -ExpandProperty IPAddress
}
Get-IpAddress

The last line executes the function call for Get-IpAddress, which returns the computer's IPv4 address in xxx.xxx.xxx.xxx format rather than the full IP address configuration that could exceed more than 100 lines of output. The function call needs to follow the function declaration; otherwise, PowerShell will return an error.

Working with functions inline is not difficult until you have many scripts to maintain. Anytime you improve a function or find a bug in your code, you must find all the scripts that reference that function and update them. That can be daunting, especially if you share the script with the rest of your team or even some customers.

How to call a function: The file-based approach

A second option is to use a PowerShell call function from another script. This is the preferred approach because it separates your scripts and functions in a more organized way. This practice leads to more sophisticated execution with PowerShell when you recognize how to turn a library of several functions you use frequently into a single PowerShell module.

If you use source control as part of your script writing process, then any time you need to update the function, your commit only applies to the function, not the scripts that use the function inline. You will find the file-based method will simplify your commit history.

To start with a function call to a file, save the Get-IpAddress function in the first example to a file named Get-IpAddress.ps1.

When you write a script that depends on a function in a file, then you need to include the function in the script. To do this, use a method called dot-sourcing. The syntax for dot-sourcing is a dot followed by the path to the function file. In this example, the function file goes in the C:\Functions folder on the Windows machine. To access the function with dot-sourcing, use the following format:

. C:\Functions\Get-IpAddress.ps1

Now, in any line that follows the dot-sourcing line, you can perform the function call, as shown in the following example that logs the current IP address to a file:

. C:\Functions\Get-IpAddress.ps1
"$((Get-Date).ToShortDateString()) $(Get-IpAddress)" | Out-File C:\logs\CurrentIp.log -Append

You can schedule the script to run daily to log both the date and the computer's IP address to track any changes. The Append parameter puts the output at the bottom of the existing file.

How to call a function from another file as a module

It's also possible to call a function located in another file with the Import-Module cmdlet. Technically, this works even if the script calls a .ps1 file that contains a single function.

The cmdlet treats the file like a module. You can even return the function's filename by running Get-Module. The problem is the file isn't a module and, as such, there is little benefit to use the Import-Module cmdlet over dot-sourcing.

How to implement PowerShell functions in other ways

As you become more proficient with PowerShell, you can produce multiple functions and use them in different ways.

You can write an entire library of functions and save each to a separate file, then use dot-sourcing to call them from a script. You could even go a step further and dot-source the functions into your PowerShell profile to make them available every time you launch PowerShell.

Learn to use a PowerShell call function from another script | TechTarget (2024)
Top Articles
About the 20 Mexican Peso Gold Coin
How Do Credit Cards Work? | Capital One
Whas Golf Card
Pet For Sale Craigslist
Places 5 Hours Away From Me
Elleypoint
Brady Hughes Justified
Botw Royal Guard
Craigslist Motorcycles Jacksonville Florida
Crocodile Tears - Quest
Rainbird Wiring Diagram
Lost Ark Thar Rapport Unlock
Dr Klabzuba Okc
Richard Sambade Obituary
Calamity Hallowed Ore
Local Dog Boarding Kennels Near Me
Nwi Arrests Lake County
Gdp E124
360 Tabc Answers
Site : Storagealamogordo.com Easy Call
How to Watch the Fifty Shades Trilogy and Rom-Coms
T Mobile Rival Crossword Clue
Obituaries Milwaukee Journal Sentinel
Airtable Concatenate
Tire Plus Hunters Creek
Pioneer Library Overdrive
Jayme's Upscale Resale Abilene Photos
Doctors of Optometry - Westchester Mall | Trusted Eye Doctors in White Plains, NY
Harrison 911 Cad Log
In hunt for cartel hitmen, Texas Ranger's biggest obstacle may be the border itself (2024)
Elanco Rebates.com 2022
The Bold and the Beautiful
Japanese Pokémon Cards vs English Pokémon Cards
Grapes And Hops Festival Jamestown Ny
How To Get Soul Reaper Knife In Critical Legends
Kelley Blue Book Recalls
Myanswers Com Abc Resources
Firestone Batteries Prices
Engr 2300 Osu
The best specialist spirits store | Spirituosengalerie Stuttgart
Homeloanserv Account Login
Uc Davis Tech Management Minor
Ups Authorized Shipping Provider Price Photos
Crystal Glassware Ebay
RubberDucks Front Office
N33.Ultipro
The Cutest Photos of Enrique Iglesias and Anna Kournikova with Their Three Kids
Bf273-11K-Cl
Read Love in Orbit - Chapter 2 - Page 974 | MangaBuddy
Round Yellow Adderall
Gelato 47 Allbud
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6128

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.