Automation

 View Only
  • 1.  Date Validation fails

    Posted Jan 21, 2020 12:48 PM

    Hi,

    I am unable to validate date for I need to shutdown VM which are created for temp use.

    Please help.

    Script

    $res = Import-Csv -Path .\date.csv -UseCulture |

    ForEach-Object -Process {

    $date = $res.MyDate

    $startdate = '{0:yyyy-MM-dd}' -f $date

    $today = (Get-Date -Format yyyy-MM-dd)

    if($today -ge $startdate){

        Write-Output "Run script"

        Stop-VM -VM $res.Server -Kill -Confirm:$false

    }else{

        Write-Output "$res.Server still not expired"

    }}

    $res

    Output

    .csv contents

    Server,Mydate

    App01,12/25/2019

    App02,12/25/2020

    App03,04/24/2020



  • 2.  RE: Date Validation fails
    Best Answer

    Posted Jan 21, 2020 01:08 PM

    All properties coming from an Import-Csv are strings.

    So you have to convert/cast to DateTime first.

    Your use of the $res variable is incorrect, use the pipeline variable $_ instead.
    Referencing a property in a string requires a specific format.

    Import-Csv -Path .\date.csv -UseCulture |

    ForEach-Object -Process {

        $date = [DateTime]$_.MyDate

        $startdate = '{0:yyyy-MM-dd}' -f $date

        $today = (Get-Date -Format yyyy-MM-dd)


        if($today -ge $startdate){

            Write-Output "Run script"

            Stop-VM -VM $_.Server -Kill -Confirm:$false

        }else{

            Write-Output "$($_.Server) still not expired"

        }

    }



  • 3.  RE: Date Validation fails

    Posted Jan 21, 2020 05:09 PM

    That worked. Thank you very much LucD. :smileyhappy: