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
Running a PowerShell script from the Command Prompt If you would like to run a PowerShell script in CMD, you'll need to execute it by calling the PowerShell process with the -File parameter, as shown below: PowerShell -File C:\TEMP\MyNotepadScript. ps1. PowerShell -File C:\TEMP\MyNotepadScript.
You can run scripts with parameters in any context by simply specifying them while running the PowerShell executable like powershell.exe -Parameter 'Foo' -Parameter2 'Bar' . Once you open cmd.exe, you can execute a PowerShell script like below.
To run Powershell commands from the command prompt or cmd, we need to call the PowerShell process PowerShell.exe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With