How to Properly Check if a Day is Monday in PowerShell?

0
1
Asked By QuickBooker30932 On

I'm working on a script in PowerShell that needs to identify the day of the week. I'm using this line to get the day: `$DoWk = (get-date $searchDate).dayofweek`, and that seems to work fine when I use it with a switch statement. However, when I try to check if the day is Monday with this condition: `if ($DoWk -ne Monday) { write-host "blah blah blah" }`, I get an error that says, "You must provide a value expression following the '-ne' operator." What am I doing wrong? Thanks!

5 Answers

Answered By TechWhiz42 On

You can also be more precise using the enum directly. Instead of a string, use the enum value: `if ($DoWk -ne [System.DayOfWeek]::Monday) { ... }`. This approach makes it clearer that you're working with enum values, which could be a better practice.

Answered By PowerShellMaster On

Remember that `$DoWk` holds a system enum value, not a string. That's why you're seeing the error. Just putting quotes around 'Monday' will fix it. Also, check out how PowerShell does type coercion for comparisons.

NerdyNinja -

Totally agree! Also, using a `switch` statement might simplify your code if you have multiple day checks.

CuriousDev -

Valid point! A `switch` is usually more efficient if you're dealing with more than just Monday.

Answered By ScriptGuru182 On

When you say `if ($DoWk -ne Monday)`, PowerShell tries to evaluate `Monday` as a command or variable. Since it's undefined, it throws an error. Always ensure to use quotes!

Answered By SyntaxSamurai On

In PowerShell, some constructs expect a value expression. If you're using something like comparing with `0 -ne (get-childitem)`, it's getting parsed cleverly. Your `Monday` without parentheses is treated as an expression that's evaluated, leading to the exception you received.

Answered By CleverCoder88 On

It looks like you're missing quotes around 'Monday'. Your line should be: `if ($DoWk -ne 'Monday') { write-host "blah blah blah" }`. That way, PowerShell understands you're checking against a string.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.