Calling a specific PowerShell function from the command line

Powershell

Powershell Problem Overview


I have a PowerShell script that contains several functions. How do I invoke a specific function from the command line?

This doesn't work:

powershell -File script.ps1 -Command My-Func

Powershell Solutions


Solution 1 - Powershell

You would typically "dot" the script into scope (global, another script, within a scriptblock). Dotting a script will both load and execute the script within that scope without creating a new, nested scope. With functions, this has the benefit that they stick around after the script has executed. You could do what Tomer suggests except that you would need to dot the script e.g.:

powershell -command "& { . <path>\script1.ps1; My-Func }"

If you just want to execute the function from your current PowerShell session then do this:

. .\script.ps1
My-Func

Just be aware that any script not in a function will be executed and any script variables will become global variables.

Solution 2 - Powershell

The instruction throws the error message below. The dot is needed before the name of the file name to load it into memory, as Keith Hill suggested.

MyFunction: The term 'MyFunction' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Solution 3 - Powershell

This solution works with powershell core:

powershell -command "& { . .\validate.ps1; Validate-Parameters }" 

Solution 4 - Powershell

Perhaps something like

powershell -command "& { script1.ps; My-Func }"

Solution 5 - Powershell

If it's a .psm1 file (as opposed to .ps1) then call this instead:

powershell -command "& { Import-Module <path>\script1.psm1; My-Func }"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionripper234View Question on Stackoverflow
Solution 1 - PowershellKeith HillView Answer on Stackoverflow
Solution 2 - PowershellLaszlo PinterView Answer on Stackoverflow
Solution 3 - PowershellAbu BelalView Answer on Stackoverflow
Solution 4 - PowershellTomer GabelView Answer on Stackoverflow
Solution 5 - PowershelltwasbrilligView Answer on Stackoverflow