58

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ripper234
  • 222,824
  • 274
  • 634
  • 905

5 Answers5

121

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.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • +1, the second code snippet was just what i needed, to do a simple debug of separate functions in a script file from ISE – hello_earth Jul 18 '11 at 12:54
  • 1
    In the second code snippet, you can surround the code with `& { ... }` as in `& { . .\script1.ps1; My-Func }` to avoid scope pollution. – Tahir Hassan Dec 17 '15 at 19:28
  • 6
    If you have parameters on the function, put them after the function name e.g. powershell -command "& { . "C:\script.ps1"; MyMethod "arg1" "arg2" }" – JsAndDotNet Aug 18 '17 at 14:36
6

This solution works with powershell core:

powershell -command "& { . .\validate.ps1; Validate-Parameters }" 
fjsv
  • 705
  • 10
  • 23
Abu Belal
  • 215
  • 1
  • 3
  • 7
5

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.

Laszlo Pinter
  • 485
  • 5
  • 12
4

Perhaps something like

powershell -command "& { script1.ps; My-Func }"
Tomer Gabel
  • 4,104
  • 1
  • 33
  • 37
1

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

powershell -command "& { Import-Module <path>\script1.psm1; My-Func }"
twasbrillig
  • 17,084
  • 9
  • 43
  • 67