0

I have a couple of functions I want to build out in a script file.

How can I call the functions from the command line using arguments? I know how to do this for variables but not for functions.

Here is my code so far:

param (
    $test
)

function Powershellversion{
    $PSVersionTable.PSVersion
}

$test = Powershellversion

I want something like this:

> powershelltests.ps1 Powershellversion

Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      1      3                  

Instead I get this:

> powershelltests.ps1 Powershellversion
# Nothing shows up

Thank you for your time,

2
  • 1
    So you want to accept a parameter argument that's the name of a function and then invoke that function? Commented Jun 17, 2021 at 20:41
  • Yeah exactly! I have a python app that I am using and I need to microsoft's exchange online powershell module in my app. I have some specific stuff I want to do like, create emails, and reset emails. so I made functions for them. Now I want to call those functions when I need to using python which means I need them passed as CLI arguments. if that makes any sense?? Commented Jun 17, 2021 at 20:43

1 Answer 1

1

If you want to invoke a function based on a variable containing the function name, use the invocation operator &:

param(
  [string]$command
)

function Get-PowerShellVersion {
  return $PSVersionTable
}

& $command

At which point you can run:


> .\powershellscript.ps1 Get-PowerShellVersion

Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      1      3                  
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for helping me with this concept. I can now learn about how this works and apply it in my script in a broader manner.