tkj80
tkj80

Reputation: 211

Powershell Combine Switch Statement

I have the following Powershell code:

$dow = (get-date).DayOfWeek
switch($dow) {{"Sunday"}{$report_Day = (Get-Date).AddDays(-2).Day}{"Monday", "Tuesday", "Wednesday", "Thursday"}{$report_Day = (Get-Date).Day}}
switch($dow) {{"Sunday"}{$report_Month = (Get-Date).AddDays(-2).Month}{"Monday", "Tuesday", "Wednesday", "Thursday"}{$report_Month = (Get-Date).Month}}

Wonder if it is possible to combine the 2 switch statements into 1 - something such as:

$dow = (get-date).DayOfWeek
switch($dow) {{"Sunday"}{$report_Day = (Get-Date).AddDays(-2).Day, $report_Month = (Get-Date).AddDays(-2).Month}{"Monday", "Tuesday", "Wednesday", "Thursday"}{$report_Day = (Get-Date).Day, $report_Month = (Get-Date).Month }}

I tested it it wouldn't work but I wonder if there is a mean to combine them.

Thank you

Upvotes: 0

Views: 458

Answers (1)

alroc
alroc

Reputation: 28174

First: Do yourself, and anyone who will read your code in the future, a favor and format your code so that it's readable. Whitespace doesn't cost you anything and it will save you difficulty later on.

Second: What does your code do on Friday & Saturday?

The issue is the commas between the statements in your switch statement. They should be separate lines (again, formatting will help you) or if you must put them on the same line, terminate each statement with a semicolon (;).

$dow = (get-date).DayOfWeek
switch ($dow) {
    "Sunday" {
        $report_Day = (Get-Date).AddDays(-2).Day;
        $report_Month = (Get-Date).AddDays(-2).Month;
        break
    }
    {($_ -eq "Monday") -or ($_ -eq "Tuesday") -or ($_ -eq "Wednesday") -or ($_ -eq "Thursday")} {
        $report_Day = (Get-Date).Day;
        $report_Month = (Get-Date).Month
        break
    }
}

Upvotes: 1

Related Questions