Powershell 通过函数传递字符串并始终获取$null变量
我在一个函数的开头使用了以下内容,该函数用于查询计算机中的各种wmi对象。如果仅运行just get_卷,则应使用127.0.0.1。似乎当我在没有任何字符串的情况下运行get_volumes时,它会直接传递到else段。实现这一目标的正确或更好的方法是什么Powershell 通过函数传递字符串并始终获取$null变量,powershell,scripting,Powershell,Scripting,我在一个函数的开头使用了以下内容,该函数用于查询计算机中的各种wmi对象。如果仅运行just get_卷,则应使用127.0.0.1。似乎当我在没有任何字符串的情况下运行get_volumes时,它会直接传递到else段。实现这一目标的正确或更好的方法是什么 PS> function get_volumes([string]$a){ if ($a -eq $null){ write-host 'Using localhost' $a = '127.0.0.1' }e
PS> function get_volumes([string]$a){
if ($a -eq $null){
write-host 'Using localhost'
$a = '127.0.0.1'
}else{ write-host 'Using' $a}
}
PS>get_volumes
Using
谢谢
$a
是一个空字符串,而不是$null
。请尝试以下方法:
function Get-Volumes([string]$IPAddress = '127.0.0.1'){
Write-Host "Using $IPAddress"
}
请注意,当用户没有为参数提供参数时,可以设置默认值。这非常有效。我不知道empty和$null之间的区别,也不知道如何设置默认值。谢谢你,基思!