VMware Cloud Community
ganapa2000
Hot Shot
Hot Shot
Jump to solution

Date Validation fails

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

pastedImage_0.png

.csv contents

Server,Mydate

App01,12/25/2019

App02,12/25/2020

App03,04/24/2020

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

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"

    }

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

Reply
0 Kudos
2 Replies
LucD
Leadership
Leadership
Jump to solution

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"

    }

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
ganapa2000
Hot Shot
Hot Shot
Jump to solution

That worked. Thank you very much LucD. Smiley Happy

Reply
0 Kudos