2 Replies Latest reply on Jan 21, 2020 9:08 AM by ganapa2000

    Date Validation fails

    ganapa2000 Hot Shot

      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

        • 1. Re: Date Validation fails
          LucD Guru
          vExpertCommunity WarriorsUser Moderators

          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: http://lucd.info | Twitter: @LucD22 | PowerCLI Reference co-author: http://tinyurl.com/hkn4glz
          • 2. Re: Date Validation fails
            ganapa2000 Hot Shot

            That worked. Thank you very much LucD.