我有一个很好的PowerShell功能,我想提示"请输入一个值"如果我得到一个空字符串,如果修剪后的参数为空则不处理。
function Find-Process([String] $AppName){
netstat -ano | Select-String $AppName
}
答案 0 :(得分:2)
如果用户未向AppName参数提供任何值,则会提示用户输入值。您还可以将AppName参数设置为Mandatory。
function Find-Process([String] $AppName){
If ([string]::IsNullOrEmpty($AppName)) { $AppName = Read-Host 'Please enter a value' }
If ($AppName) { netstat -ano | Select-String $AppName
}
Else {
'Value not provided'
}
}
#
function Find-Process{
param(
[parameter(Mandatory=$true)]
[String] $AppName
)
netstat -ano | Select-String $AppName
}
答案 1 :(得分:2)
对于参数,您可以使用ValidateNotNullOrEmpty
:
function Find-Process{
param(
[ValidateNotNullOrEmpty()]
[String] $AppName
)
Write-Host $Appname
}
提供null或空参数时的错误消息:
Find-Process:无法验证参数'AppName'的参数。参数为null或空。提供一个 参数不为null或为空,然后再次尝试该命令。
如果您不希望函数在没有该参数的情况下运行,您可能需要考虑[parameter(Mandatory=$true)]
。
答案 2 :(得分:1)
您应该使用参数验证来检查值是否为空,而不是建议提示,如果不是。
使用此代码,如果$AppName
为空或为空
function Find-Process{
Param(
[ValidateNotNullOrEmpty()][String]$AppName
)
netstat -ano | Select-String $AppName
}