How to run a PowerShell function from a command line?

Brajagopal Tripathi
2 min readNov 5, 2023
Photo by Markus Spiske on Unsplash

There are two main ways to run a PowerShell function from the command line:

  • Using the & operator: The simplest way to run a PowerShell function from the command line is to use the ampersand (&) operator followed by the name of the function. For example, if you have a function called My-Function, you can run it by typing the following command into the command prompt:
& My-Function
  • Using the dot sourcing (.ps1) file: Another way to run a PowerShell function from the command line is to dot source (.ps1) the file that contains the function. To do this, type the following command into the command prompt:
.\ <filename>.ps1

Replace <filename> with the name of the file that contains the function. This will load the function into the current PowerShell session, and you can then run it by typing its name into the command prompt.

Example:

.\ MyScript.ps1
My-Function

If the function takes parameters, you can pass them to the function by typing them after the function name. For example, if the My-Function function takes a parameter called Name, you can run it by typing the following command into the command prompt:

& My-Function -Name "John Doe"

In addition to these two methods, you can also run a PowerShell function from a command line by using the Invoke-Expression cmdlet. However, this method is not as common as the other two methods.

--

--

Brajagopal Tripathi

Student of Computer Application and Network Administration || Cloud Technology and Cyber Security Enthusiast