Search code examples
powershellpowershell-4.0

How to Exclude Weekends and holidays using powershell


enter image description hereI am trying to write code in PowerShell to exclude weekends and holidays, but I'm getting errors, can you please help me with that?

$a = Get-Date -format "yyyy-MM-dd"
#Get-Date -format "dddd yyyy-MM-dd"

if($a.DayOfWeek -eq 'Tuesday')
{
    Write-Host "tuesday"
}
else
{
    Write-Host "false"
}

Solution

  • It is recommended to use Set-StrictMode for your development scripts to identify code issues.

    From Get-Help Set-StrictMode -online:

    The Set-StrictMode cmdlet configures strict mode for the current scope and all child scopes, and turns it on and off. When strict mode is on, PowerShell generates a terminating error when the content of an expression, script, or script block violates basic best-practice coding rules.

    You get an exhaustive answer to your question immediately using Set-StrictMode:

    Set-StrictMode -Version latest
    $a=Get-Date  -format "yyyy-MM-dd"
    $a.DayOfWeek -eq 'Tuesday'
    
    The property 'DayOfWeek' cannot be found on this object. Verify that the property exists.
    At line:3 char:1
    + $a.DayOfWeek -eq 'Tuesday'
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
        + FullyQualifiedErrorId : PropertyNotFoundStrict