本文介绍了功能中空参数不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 函数TestFunction {
Param([int] $ Par1,[string]如果($ Par1 -ne $ Null){Write-OutputPar1 = $ Par1}
If($ Par2 -ne $ Null -or $ Par2 - $ Par2,[string] $ Par3)
If如果($ Par3 -ne $ Null){Write-OutputPar3 = $ Par3}
}
TestFunction - 写入输出Par2 = $ Par2}
Par1 1 -Par3'par3'

...输出结果为:

  Par1 = 1 
Par2 =
Par3 = par3

即使我没有向> $ Par2 变量传递任何东西,它仍然不是空或空。发生了什么事情,以及如何重写语句,以便第二个If语句的计算结果为False,并且脚本块没有执行?

(我添加了 - 或者$ Par2 -ne''只是为了测试,它的行为与没有它一样。)

解决方案

你的程序中有一个逻辑错误: $ Par2 will always 不等于 $ null 不等于''



要修正逻辑,您应该使用 - 和而不是 - 或在这里:
$ b

If($ Par2 -ne $ Null -and $ Par2 -ne'' ){Write-OutputPar2 = $ Par2}

然而,因为您铸造了 $ Par2 参数传递给函数参数列表中的字符串:

  Param([int] $ Par1,[string] $ Par2,[st ring] $ Par3)
^^^^^^^^

检查 $ Par2 -ne $ Null 是不必要的,因为 $ Par2 将始终为字符串类型(如果您不给它值,它将被分配给'')。所以,你应该写下:
$ b

  If($ Par2 -ne''){Write-输出Par2 = $ Par2} 

或者,因为''评估为false,你可能会这样做:
$ b

  If($ Par2) {Write-OutputPar2 = $ Par2} 


Given this basic function:

Function TestFunction {
    Param ( [int]$Par1, [string]$Par2, [string]$Par3 )
    If ($Par1 -ne $Null) { Write-Output "Par1 = $Par1" }
    If ($Par2 -ne $Null -or $Par2 -ne '') { Write-Output "Par2 = $Par2" }
    If ($Par3 -ne $Null) { Write-Output "Par3 = $Par3" }
}
TestFunction -Par1 1 -Par3 'par3'

...the output is:

Par1 = 1
Par2 = 
Par3 = par3

Even though I didn't pass anything into the $Par2 variable, it still isn't Null or empty. What happened, and how can I rewrite the statement so that the second If-statement evaluates as False and the script-block does not get executed?

(I added the -or $Par2 -ne '' just to test, it behaves the same with and without it.)

解决方案

You have a logic error in your program: $Par2 will always be not equal to $null or not equal to ''.

To fix the logic, you should use -and instead of -or here:

If ($Par2 -ne $Null -and $Par2 -ne '') { Write-Output "Par2 = $Par2" }

However, because you casted the $Par2 argument to a string in the function's argument list:

Param ( [int]$Par1, [string]$Par2, [string]$Par3 )
                    ^^^^^^^^

the check for $Par2 -ne $Null is unnecessary since $Par2 will always be of type string (if you do not give it a value, it will be assigned to ''). So, you should actually write:

If ($Par2 -ne '') { Write-Output "Par2 = $Par2" }

Or, because '' evaluates to false, you might just do:

If ($Par2) { Write-Output "Par2 = $Par2" }

这篇关于功能中空参数不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 15:26