3

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
  • 2
    The main reason is you're setting the function, you'd need to the call the function compare-numbers though i'd be interested as to know why your code isn't correctly working - when I'm running it it's refusing to ask for $b for me and I'm unsure why. Commented Oct 15, 2019 at 10:08
  • The return (exit 1) will throw an error because exit is not known. Replace throw "an error occured!" with throw $_ to see the error. Commented Oct 15, 2019 at 10:54

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

thank you really much, the artivel was exactly what i needed and now my script does what it should do
1

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.

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.