Chris Herzog
Chris Herzog

Reputation: 29

Powershell if-statement passing in parameter

param($addr)
$file = get-content $addr

if($addr -eq $null){
        "Please use a valid parameter"
}
else{
        if ($addr -ne './*'){
                write-host $addr
        }
        else{
                write-host $file
        }

}

OUPUT:

./ipAddress.txt

CONTENT:

8.8.8.8
127.0.0.1
208.67.222.222

If I put $file out of the if statement then it works. However, I want to be able to say if the user inputs either a file or an ip address then do this...

Upvotes: 1

Views: 12718

Answers (2)

briantist
briantist

Reputation: 47862

Stop relying on positional parameters. Use named parameters with parameter sets, and remove the ambiguity:

[CmdletBinding(DefaultParameterSetName='ByFile')]
param(
    [Parameter(
        Mandatory=$true,
        ParameterSetName='ByFile'
    )]
    [ValidateScript( { $_ | Test-File } )]
    [String]
    $Path ,

    [Parameter(
        Mandatory=$true,
        ParameterSetName='ByIP'
    )]
    [System.Net.IPAddress[]]
    $IPAddress
)

$ipAddresses = if ($PSCmdlet.ParameterSetName -eq 'ByFile') {
    $Path | Get-Content
} else {
    $IPAddress
}

foreach ($ip in $ipAddresses) {
    # do something with the IP
}

Invoke it like this:

./get-Ping.ps1 -File ./fileOfIPs.txt

or

./get-Ping.ps1 -IPAddress 10.1.2.3
./get-Ping.ps1 -IPAddress 10.0.0.10,10.0.0.20,8.8.8.8

It even supports multiple IPs given directly.

Alternative

If you must support a positional parameter that can be either, then I suggest testing the IP first:

param($addr)

$ips = if ($addr -as [System.Net.IPAddress]) { # it can be interpreted as an IP
    $addr
} else {
    $addr | Get-Content
}

foreach ($ip in $ips) {
    #do something
}

Upvotes: 4

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10809

The problem is your comparison in the else clause. -ne only matches - or rather, not-matches - an exact string, without honoring wildcards. Instead, you should use -notlike: if ($addr -notlike "./*") {...}. Note that you'll still have problems if you supply a full path to a file (e.g., D:\Foo\IPs.txt), but the comparison here is your specific problem given the input for your example.

Take a look at Get-Help about_Comparison_Operators

Upvotes: 3

Related Questions