George Murphy
George Murphy

Reputation: 1097

Find if PowerShell argument is an empty string and prompt for input

I have a nice PowerShell function that I want to prompt "please enter a value" if I get an empty string and not process if the trimmed argument is empty.

function Find-Process([String] $AppName){

    netstat -ano | Select-String $AppName
}

Upvotes: 1

Views: 5522

Answers (3)

Vincent K
Vincent K

Reputation: 1346

If User does not provide any value to AppName Parameter, it will prompt the user for a value. You can also make the AppName parameter as 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
}

Upvotes: 4

Manu
Manu

Reputation: 1742

You should use parameters validation to check if the value is empty instead of propose a prompt if not.

With this code, the function cannot be called if $AppName is empty or null

function Find-Process{
    Param(
        [ValidateNotNullOrEmpty()][String]$AppName
    )
    netstat -ano | Select-String $AppName
}

Upvotes: 1

G42
G42

Reputation: 10019

For parameters, you can use ValidateNotNullOrEmpty:

function Find-Process{
    param(
        [ValidateNotNullOrEmpty()]
        [String] $AppName
    )
    Write-Host $Appname
}

Error message when a null or empty argument is provided:

Find-Process : Cannot validate argument on parameter 'AppName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.


You may want to consider [parameter(Mandatory=$true)] if you do not want the function to run without that argument.

Upvotes: 3

Related Questions