datepowershellvariablestostringwrite-host

Subtract/Add days to a predefined date using Write-Host


I am trying to display milestones. I tried below but I get an error that displays Method invocation failed because [System.String] does not contain a method named 'AddDays'. I have predefined $lastmodified in a previous line and it is 12/28/2015 0:00

$predetermined=[system.datetime]$LastModified
$date= ($predetermined).AddDays(30).ToString("MM/dd/yyyy:")

$date5 = ($date).AddDays(-15).ToString("MM/dd/yyyy:")
$date4 = ($date).AddDays(-12).ToString("MM/dd/yyyy:")
$date3 = ($date).AddDays(-9).ToString("MM/dd/yyyy:")
$date2 = ($date).AddDays(-6).ToString("MM/dd/yyyy:")
$date1 = ($date).AddDays(-3).ToString("MM/dd/yyyy:")

write-host -foregroundcolor Green "$date5 Action 1"
write-host -foregroundcolor Green "$date4 Action 2"
write-host -foregroundcolor Green "$date3 Action 3"
write-host -foregroundcolor Green "$date2 Action 4"
write-host -foregroundcolor Green "$date1 Action 5"
write-host -foregroundcolor Green "$date Action 6"

My output should say

12/23/2015: Action 1"
12/26/2015: Action 2"
12/19/2015: Action 3"
12/22/2015: Action 4"
12/25/2015: Action 5"
12/28/2015: Action 6"

Solution

  • Do something like this in your code:

    function Get-DateFmt1
    {
        param (
            [Parameter(Mandatory=$true, Position=0)]
            [DateTime] $Date
        )
    
        $Date.ToString("MM/dd/yyyy")
    }
    
    $LastModified = [DateTime]::Parse('12/28/2015')
    # ....
    $predetermined=[DateTime]$LastModified
    $date = ($predetermined).AddDays(30)
    
    $date5 = $date.AddDays(-15)
    $date4 = $date.AddDays(-12)
    $date3 = $date.AddDays(-9)
    $date2 = $date.AddDays(-6)
    $date1 = $date.AddDays(-3)
    
    Write-Host -Foregroundcolor Green "$($date5.ToString("MM/dd/yyyy")): Action 1"
    Write-Host -Foregroundcolor Green "$($date4.ToString("MM/dd/yyyy")): Action 2"
    Write-Host -Foregroundcolor Green "$($date3.ToString("MM/dd/yyyy")): Action 3"
    # or write a helper function if that makes sense to you
    Write-Host -Foregroundcolor Green "$(Get-DateFmt1 $date2): Action 4"
    Write-Host -Foregroundcolor Green "$(Get-DateFmt1 $date1): Action 5"
    Write-Host -Foregroundcolor Green "$(Get-DateFmt1 $date): Action 6"