0

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
}
1
  • $args.split -> $args.split(), although you might want to use a variable name other than args Commented Feb 24, 2021 at 16:07

1 Answer 1

1

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*"
Sign up to request clarification or add additional context in comments.

1 Comment

Great, thank you! The occupied name "$args" made me doubt my mind. Also nice solution with the array of strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.