PowerShell Script does not generate an error, but is not working correctly

Viewed 79

I just want to write a basic PowerShell script which compares two numbers. When I call my script via .\Compare-Numbers.ps1 -a 3 -b 3 nothing happens.

function Compare-Numbers {

    param(
    [Parameter(Mandatory=$True, HelpMessage="Please enter two numbers")]
    [int]$a, 
    [int]$b
    )

    try {
        if($a -eq $b) {
            Write-Host "the given numbers are equal"
            return (exit 0)
        }
        else {
            Write-Host "the given numbers are not equal"
            return (exit 1)
        }
    }
    catch {
        throw "an error occured!"
        exit $LASTEXITCODE
    }
}

I would expect that the write-host command writes the text in my command prompt, but - nothing happens.

2 Answers

I think you're a little confused. You created a function and saved it to a file. If you run the file, PowerShell will say:

yep, function loaded, nothing else to do, bye!

If you plan to run this from a file, you will need to change your approach a little. This article perfectly describes your current situation and issue.

This is what your script would end up looking like:

Param($intOne = 5,
$intTwo = 3
)
Function add-numbers
{
Param($intOne,
$intTwo
)
$intOne + $intTwo
} #end function add-numbers
# *** entry point to script ***
add-numbers -intOne $intOne -inttwo $intTwo

A Bit of a late reply but I was interested in your code and wanted to correct the value prompting:

function Number-comparison {

    param(
    [Parameter(Mandatory=$True, HelpMessage="text")][int]$a1,
    [Parameter(Mandatory=$True, HelpMessage="text")][int]$b1

    )

If we use the above it will prompt the user correctly.

Related