Search code examples
powershellcommand-lineparametersarguments

Powershell - How Do I Pass Command Line Arguments to a Function in a Module?


I've written a PowerShell module to show help when the user requests it with a command line parameter like -show help-topic. I import it into the main script with this statement:

Import-Module Help-Module -ArgumentList $args

Scripts call a module function like this:

Show-Help $args

This is the called function:

function Show-Help {
<#
.SYNOPSIS
Looks for command line arguments indicating user requested help, and if they are present, displays the
requested help.
.OUTPUTS
$true if one or more help requests were found and answered, else $false.
Throws an error if a help request was malformed.
#>
   Write-Debug "Inside Show-Help"
   if ([string]::IsNullOrWhiteSpace($args)) {                     # If no arguments
      return $false                                               # Nothing to do
   }
   if ($args.Length -gt 0 -and $args[0] -eq "-help") {            # If just a generic help request
      Show-ScriptOverview                                         # Show script overview
      return $true                                                # And we’re done
   }                                                              # Otherwise
   foreach ($argument in $args) {                                 # Examine each argument
      Write-Host "Argument type is $($argument.getType())"
      $argarray = $argument.split(' ')                  
      if ($argarray.length -eq 2 -and $argarray[0] -eq "-show") { # If it’s a “show” request
         switch ($topic = $($argarray[1])) {                      # What is user requesting?
            default {throw "Sorry, we don’t what '$topic' means"} # Unless we don’t recognize it
         }
         return $true
      }
   }
}

It outputs Argument type is System.Object[]

Then it fails on the call to $argument.split(' ') with this message:

Method invocation failed because [System.Object[]] does not contain a method named 'split'

How can I pass command line arguments to a module function in a data type that I can get string values from?


Solution

  • Replace Show-Help $args with:

    Show-Help @args
    

    That is, use splatting in order to pass the arguments that your script received through to the Show-Help function.

    Note that for the purpose of relaying arguments it is irrelevant whether your function is defined in a module or not.


    As for what you tried:

    Show-Help $args

    passes the automatic $args variable as a single argument that is an array to Show-Help, which explains why the - redefined inside Show-Help - $args variable saw an array in its first - and only - element, $args[0]