none
How to handle error in Get-Date RRS feed

  • Question

  • I have a file of dates and time in the format: "yyyy-mm-dd","HH:MM", etc. Some lines however will not have a valid date and time, e.g. "#" for a comment. I have been taking the approach below to convert the date and time. The problem is that it outputs an error to the console which I don't want. Instead I want the line skipped.

    This illustrates my problem:

    PS C:\> Get-Date -Date "foo" -ErrorAction:Ignore -ErrorVariable MyError
    Get-Date : Cannot bind parameter 'Date'. Cannot convert value "foo" to type "System.DateTime". Error: "The string was
    not recognized as a valid DateTime. There is an unknown word starting at index 0."
    At line:1 char:16
    + Get-Date -Date "foo" -ErrorAction:Ignore -ErrorVariable MyError
    +                ~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException
        + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand



    • Edited by aenagy Wednesday, April 22, 2015 12:23 AM speeling mistake
    Wednesday, April 22, 2015 12:17 AM

Answers

  • Bill:

    That works.

    I'm a bit surprised that the solution requires resorting try/catch.  Why doesn't the ErrorAction and ErrorVariable work?

    Wednesday, April 22, 2015 5:01 PM

All replies


  • try {
      get-date "whatever"
    }
    catch [System.Management.Automation.ParameterBindingException] {
      write-host "Unable to parse that date"
    }
    


    -- Bill Stewart [Bill_Stewart]

    Wednesday, April 22, 2015 1:31 AM
    Moderator
  • Bill:

    That works.

    I'm a bit surprised that the solution requires resorting try/catch.  Why doesn't the ErrorAction and ErrorVariable work?

    Wednesday, April 22, 2015 5:01 PM
  • The ParameterBindingException exception is a terminating error.

    ErrorAction/ErrorVariable are for non-terminating errors.


    -- Bill Stewart [Bill_Stewart]

    Wednesday, April 22, 2015 5:50 PM
    Moderator