# Create an exception for the script

**URL:** <https://forums.powershell.org/t/create-an-exception-for-the-script/10376>\
**Category:** PowerShell Help\
**Created:** [March 23, 2018, 2:00pm UTC](https://forums.powershell.org/t/create-an-exception-for-the-script/10376 "2018-03-23T14:00:55Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![rafhaelcampelo](https://avatars.discourse-cdn.com/v4/letter/r/e19adc/32.png) [@rafhaelcampelo](https://forums.powershell.org/u/rafhaelcampelo)\
**Post date:** [March 23, 2018, 2:00pm UTC](https://forums.powershell.org/t/create-an-exception-for-the-script/10376/1 "2018-03-23T14:00:55Z")

</div>

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) "

```

}

---

<div class="post-metadata">

**Author:** ![matt-bloomfield](https://avatars.discourse-cdn.com/v4/letter/m/dec6dc/32.png) [@matt-bloomfield](https://forums.powershell.org/u/matt-bloomfield)\
**Post date:** [March 23, 2018, 5:39pm UTC](https://forums.powershell.org/t/create-an-exception-for-the-script/10376/2 "2018-03-23T17:39:31Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![ta11ow](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/ta11ow/32/131_2.png) [@ta11ow](https://forums.powershell.org/u/ta11ow)\
**Post date:** [March 24, 2018, 6:31pm UTC](https://forums.powershell.org/t/create-an-exception-for-the-script/10376/3 "2018-03-24T18:31:16Z")

</div>

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
```

---

<div class="post-metadata">

**Author:** ![rafhaelcampelo](https://avatars.discourse-cdn.com/v4/letter/r/e19adc/32.png) [@rafhaelcampelo](https://forums.powershell.org/u/rafhaelcampelo)\
**Post date:** [March 26, 2018, 6:46am UTC](https://forums.powershell.org/t/create-an-exception-for-the-script/10376/4 "2018-03-26T06:46:59Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![ta11ow](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/ta11ow/32/131_2.png) [@ta11ow](https://forums.powershell.org/u/ta11ow)\
**Post date:** [March 26, 2018, 11:29am UTC](https://forums.powershell.org/t/create-an-exception-for-the-script/10376/5 "2018-03-26T11:29:07Z")

</div>

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](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-6)

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:36pm UTC](https://forums.powershell.org/t/create-an-exception-for-the-script/10376/6 "2024-05-16T20:36:06Z")

</div>


