简体   繁体   English

Powershell - 在循环、变量初始化和 if 语句中调用 function

[英]Powershell - calling function in loops, variable initialisation and if statements

Like the title said, I have some trouble using functions in loops, variable initialisation and if statements as conditions.正如标题所说,我在循环中使用函数、变量初始化和 if 语句作为条件时遇到了一些麻烦。 However, if I just call the fuction out of the blue it does work fine, leading me to think the problem is how I call the function and not the function itself, I may be wrong though.但是,如果我只是突然调用函数,它确实可以正常工作,这让我认为问题是我如何调用 function 而不是 function 本身,但我可能错了。

Here's the function I'm trying to call:这是我要拨打的 function:

function checkAlphaNumerical {
    param (
        #First, the string to validate, then a string to append to the error message
        $stringToValidate, $stringDesc
    )
    if ($stringToValidate -notmatch '^[a-z0-9]+$') {
        Write-Output ("Invalid $($stringDesc)")
        return $false
    }
    else {
        return $true
    }
}

Since I use return $true and return $false on both possible path of the function, Powershell console should output me True or False depending on the string value.由于我在 function 的两个可能路径上使用return $truereturn $false ,因此 Powershell 控制台应该 output me TrueFalse ,具体取决于字符串值。

Here's the only scenario where calling the function works:这是调用 function 的唯一情况:

checkAlphaNumerical $testinput "test"

Here's three example where it does not work:这是它不起作用的三个示例:

 do {
    $testinput = Read-Host -Prompt "Enter string"
} while (!(checkAlphaNumerical $testinput "test"))
 if (checkAlphaNumerical $testinput "test") {
            #stuff
        }
$someBool = checkAlphaNumerical $testinput "test"

Thanks in advance for your help.在此先感谢您的帮助。

It's not working as expected because your function, as written, returns a two-element object array when your test is false:它没有按预期工作,因为当您的测试为假时,您的 function 将返回一个二元素数组 object :

PS > $TestFailure = checkAlphaNumerical '%' "FailTest"
PS > $TestFailure
Invalid FailTest
False
PS > $TestFailure.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array


PS > $TestFailure[0]
Invalid FailTest
PS > $TestFailure[1]
False
PS > [bool]$TestFailure
True
PS keith>

And when the array is cast as a boolean, as it is when serving as a test conditon, it returns $True .当数组被转换为 boolean 时,就像用作测试条件时一样,它返回$True

Changing write-Output to Write-Warning will display your "Invalid...." message at the console while ensuring the return value is simply $False .write-Output更改为Write-Warning将在控制台上显示“无效...”消息,同时确保返回值只是$False Also:还:

  • In PowerShell functions, the Return statement is unnecessary.PowerShell函数中,不需要Return语句。 Any unconsumed output is returned.返回任何未使用的 output。
  • Since $stringDesc is simply a string variable, you don't need "...$($stringDesc)" in your expansion string.由于$stringDesc只是一个字符串变量,因此您不需要在扩展字符串中"...$($stringDesc)"

So a working version of your fucntion would be:所以你的功能的工作版本是:

function checkAlphaNumerical {
    param (
        #First, the string to validate, then a string to append to the error message
        $stringToValidate, $stringDesc
    )
    if ($stringToValidate -notmatch '^[a-z0-9]+$') {
        Write-Warning ("Invalid $stringDesc")
        $false
    }
    else {
        $true
    }
}

Output: Output:

PS > do {
>>     $testinput = Read-Host -Prompt "Enter string"
>> } while (!(checkAlphaNumerical $testinput "test"))
Enter string: '%'
WARNING: Invalid test
Enter string: '?'
WARNING: Invalid test
Enter string: abc
PS >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM