gargamel
gargamel

Reputation: 3

Noob question: multiple parameters for custom function in powershell

I try to simply pass two parameters to a powershell function. The seccond parameter $args keeps being empty in the function. What am I missing?

$t= "wi-fi Adapter"

if (multilike $t "*wi-fi*,*wireless*,*wan miniport*" ) {
    Write-Host "True"
}

function multilike($text, $args) {
    foreach ($arg in $args.split) {
        if ($text -like $arg) {return $true}
    }
    return $false
}

Upvotes: 0

Views: 156

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174825

Two things:

Don't use $args

$args is an automatic variable, using it as a declared parameter might result in unexpected behavior

Remember to invoke Split()

$someString.Split is going to emit the method signatures of the String.Split() method overloads - in order to actuall execute the method, you need to supply a(n empty) parameter list:

function multilike($text, $patterns) {
    foreach($pattern in $patterns.Split())
    { # ...

Since you want to accept one-or-more strings as your second parameter argument, you might benefit from declaring it an array of strings:

function multilike {
  param(
    [string]$text, 
    [string[]]$patterns
  )
    foreach($pattern in $patterns) # no need to .Split() any longer
    { # ...

And then call like:

multilike $t *wi-fi*,*wireless*,"*wan miniport*"

Upvotes: 1

Related Questions