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
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.
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.
Valid point! A `switch` is usually more efficient if you're dealing with more than just Monday.
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!
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.
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.
Totally agree! Also, using a `switch` statement might simplify your code if you have multiple day checks.