Calling a specific powershell function from command line

Tag: powershell Author: czy790801 Date: 2009-08-25

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

This doesn't work:

powershell -File script.ps1 -Command My-Func

Best Answer

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

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


+1, the second code snippet was just what i needed, to do a simple debug of separate functions in a script file from ISE

Other Answer1

Perhaps something like

powershell -command "& {; My-Func }"