0

This is a small script I'm calling from an excel spreadsheet:

Param (
    [Int] $ID,
    [String] $server,
    [String] $db,
    [String] $uid,
    [String] $pw,
    [String] $Navn,
    [String] $Path
)
Try
{
Add-Type -Path $Path

foreach($i in [BrReader2.BrReader]::Main($ID, $uid, $pw, $db, $server)){if($i.Key -eq $Navn){$Data = $i}}

[BrReader2.BrReader]::WriteToTemporaryTable($Data, $ID, $uid, $pw, $db, $server)
}
Catch
{
$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage
Read-Host -Prompt "Press Enter to exit"
}

It works mostly pretty well, except for one little thing. If for some reason one of the parameters is entered in the wrong way, like if it's completely empty, it will fail there and not write out an error message. The console window will simply quickly appear and disappear again and the user might not realise what they've done wrong.

Giving a wrong path is fine, it will still enter the try/catch block and write a proper error message to the console. Giving NO path does not keep the console window open so the user can see what went wrong though.

I need to put the 'Param (...' part at the top of the script though, so I can't put it into the try/catch block. Is there any way I can write out an error message and keep the console window open if one of the parameters fail?

I'm not very experienced with powershell so there might be something obvious I'm missing.

1
  • [ValidateNotNullOrEmpty()] Commented Sep 6, 2018 at 10:07

1 Answer 1

1

If you want the parameters to be set, you can make them mandatory.

If they should contain a certain value, you can also validate them.

For example:

Param (
    [Parameter(Mandatory = $true)]
    [ValidateRange(10,99)] 
    [Int] $ID,

    [Parameter(Mandatory = $true)]
    [String] $server,

    [Parameter(Mandatory = $true)]
    [ValidateSet("sql01.contoso.local","sql02.contoso.local")] 
    [String] $db,

    [Parameter(Mandatory = $true)]
    [String] $uid,

    [Parameter(Mandatory = $true)]
    [String] $pw,

    [Parameter(Mandatory = $true)]
    [String] $Navn,

    [Parameter(Mandatory = $true)]
    [ValidateScript({Test-Path $_ -PathType 'Container'})] 
    [String] $Path
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.