Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a specific PowerShell function from the command line

Tags:

powershell

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 
like image 821
ripper234 Avatar asked Sep 10 '09 14:09

ripper234


People also ask

How do you call a PowerShell script from the command line?

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.

How do I run a PowerShell script from the command line with parameters?

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.

Can you run PowerShell commands from cmd?

To run Powershell commands from the command prompt or cmd, we need to call the PowerShell process PowerShell.exe.


1 Answers

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.

like image 139
Keith Hill Avatar answered Oct 13 '22 06:10

Keith Hill