Author Posts

May 14, 2018 at 4:20 pm

I'm not good with Powershell and I've been struggling to make a simple script that takes an input switch and runs a function based on the switch.

I want to run the script like this:
PS C:\> .\fig2.ps1 -000
You used the 000 Option

Unfortunately this is what happens with I run it with or without any switch:
PS C:\> .\fig2.ps1 -001
You used the 000 Option
You used the 001 Option
You used the 002 Option

param([switch] $000, [switch] $001, [switch] $002)

if($000 = $true)
{
    Write-Host "You used the 000 Option"
}
if($001 = $true)
{
    Write-Host "You used the 001 Option"
}
if($002 = $true)
{
    Write-Host "You used the 002 Option"
}
exit

I know I'm probably missing quite a lot but I can't seem to figure out where to start learning.
Any advice would be welcome.

May 14, 2018 at 4:39 pm

Good morning Nick

First off if you are just starting out I would highly recommend picking up Powershell In A Month Of Lunches (3rd edition). This book is the number one book I always recommend people to use when first learning PowerShell.

That being said, the reason your getting the output you are getting is due to how you are evaluating your if statement. In PowerShell you need to use -eq to check if one value is equal to another. Using = sets a variable to the value on the right hand side. So in this case you were saying If switch parameter is able to be set to true then perform the following command.

I also would not use 000,001,002 as your switch name – I know when I started I tried that and ran into multiple issues. I went ahead and changed your switch names to S1,S2,S3

So using your format you can change the code to look like:


param([switch] $S1, [switch] $S2, [switch] $S3)

if($S1 -eq $true)
{
    Write-Host "You used the 000 Option"
}
if($S2 -eq $true)
{
    Write-Host "You used the 001 Option"
}
if($S3 -eq $true)
{
    Write-Host "You used the 002 Option"
}
exit

If you want to make it even easier to read:


param([switch] $S1, [switch] $S2, [switch] $S3)

if($S1)
{
    Write-Host "You used the 000 Option"
}
if($S2)
{
    Write-Host "You used the 001 Option"
}
if($S3)
{
    Write-Host "You used the 002 Option"
}
exit

Good luck on learning PowerShell!

May 14, 2018 at 4:51 pm

I'd be more inclined to do it like this

$Option = 001

switch ($Option)
{
    000 {Write-Host "You used the 000 Option"}
    001 {Write-Host "You used the 001 Option"}
    002 {Write-Host "You used the 002 Option"}
    $Null {Write-Host "You did not provide an Option"}
}

May 14, 2018 at 4:56 pm

I agree. I was just keeping the code in the same format as the original to hopefully get the point across – but yes – using switch is the more preferred way to do it.

May 14, 2018 at 5:14 pm

Thank you both!