Author Posts

March 23, 2018 at 7:30 pm

Hi
I would like to create a revision for when the correct values were not typed, I wrote this basic script of how to check if the port is active, but I do not know how to create an exception for wrong values.

Any suggestions are welcome.

$Ipaddress= Read-host "Enter the host you want to check"
$Port= Read-host "Now Enter the Port you want to check"

$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)

if($t.Connected)
{
" Port $Port is enabled on the date of: $(Get-Date)"
}
else
{
"Port $Port is inactive, could not connect port in $(Get-Date) "
}

March 23, 2018 at 11:09 pm

I'm assuming you're talking about handling when a user enters invalid values for the IP address or port.
Rather than using Read-Host, your best bet is to start working with parameters. If you use parameters you can use PowerShell's built-in validation methods.

Below is a quick example that shows validation using a regex pattern to check the IP address and a range validation to check if a valid TCP port is entered.

function Test-Port {
    
    param (

        [Parameter(Mandatory=$true)]
        [ValidatePattern("\d+\.\d+\.\d+\.\d+")]
        $ipAddress,
        
        [Parameter(Mandatory=$true)]
        [ValidateRange(1,65535)]
        $port
    )    
        
    Write-Output "$($ipAddress):$($port)"

}

#Valid values
Test-Port -ipAddress 192.168.7.1 -port 22

#Invalid port
Test-Port -ipAddress 192.168.7.1 -port 0

#Invalid IP address
Test-Port -ipAddress 192.168.7. -port 22

Note: the pattern I used is just an example; it's not a good pattern to use in the real world as it will allow invalid addresses.

March 25, 2018 at 12:01 am

Yep, parameter validation will basically do the work for you, and you should generally strive to work with it rather than create your own input methods.

but in the event you need to throw errors there are a couple of methods:

throw "error message"
# Recommended method, especially for modules
$PSCmdlet.ThrowTerminatingError("message")
# Bit of a weird way in my opinion, but does apparently work!
Write-Error "Message" -ErrorAction Stop

March 26, 2018 at 12:16 pm

Hi, Matt
I'm sorry, but I still can not create anything with the example shown.
I'm new to using powershell and I've never used a parameter.

March 26, 2018 at 4:59 pm

Basically, parameters work one of two ways. Either they work with functions, or with your script as a whole.

To define parameters for your script as a whole, place a param() block at the top of your script (or just inside the function if you're doing function parameters):

param(
    $Parameter1,
    $Parameter2
)
Write-Output $Parameter1, $Parameter2

You can think of these basically like any other variable; they can be modified later, have default values, and so on. The main difference between regular variables and parameters is that anyone calling the script can freely specify the value. Here's a quick example of how to do so, using the above example parameters:

PS C:\Path\To\> Script.ps1 -Parameter1 "Value of Parameter1" -Parameter2 -14
Value of Parameter1
-14

As you can see, even though the values were never actually specified in the Script, PS will happily pass the user's values on in and work with them. Additionally, for parameters that need specific values, you can do validation checks. For example, if you need a number between 1 and 100, but the user enters "hello" instead, you don't need to deal with it manually:

param(
    [ValidateScript(
        { $PSItem -ge 1 -and $PSItem -le 100 }
    )]
    [int]
    $Number
)
Write-Output "You picked the number $Number!"

Here, we define a type for the parameter. [int] accepts only whole numbers. That rules out the possibility of users entering random text. If they try, PowerShell will tell them it won't work, and stop processing the script. We've also added a bit of script that checks the value to make sure it's between 1 and 100. $PSItem, also commonly referenced as $_, refers to the 'current value', because that can change quite a bit. It gets used in many places, most notably things working heavily with the pipeline system. Here, it just refers to "whatever the user entered for this parameter".

For reference, here is a pretty thoroughly specified set of attributes for a parameter:

[Parameter(Position = 0, Mandatory, ParameterSetName = "Set1")]
[Alias('P1')]
[ValidateNotNullOrEmpty()]
[string]
$Parameter1

You needn't always specify all of them, and there are of course some I haven't mentioned. There are a whole host of [Validate*()] attributes for different purposes.

Here's the Microsoft documentation on advanced parameters for the full gamut:
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-6