I'm trying to filter certificates on my local machine and remove all created before 4/10/2021

PS C:\Users\juraj> $cert = Get-ChildItem Cert:\localMachine\My | Where-Object { $_.NotBefore -is [DateTime]::Today  }
Cannot convert value "14/10/2021 12:00:00 AM" to type "System.Type". Error: "Invalid cast from 'System.DateTime' to
At line:1 char:62
+ ... ocalMachine\My | Where-Object { $_.NotBefore -is [DateTime]::Today  }
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

So currently I'm testing the function but even when converted (Get-Date).ToString it ends with similar red sea of errors.

How do I go about this?

PS 5.1 in W11

  • is there anything in the Cert:\LocalMachine\My path? my system shows nothing there.
    – Lee_Dailey
    Oct 14 at 0:54
  • yes, we do have items there.. for testing, you can use root cert path Cert:\LocalMachine\CA
    – JurajB
    Oct 14 at 1:28
  • ok ... that gives me an object. now ... WHY are you testing to see if the two objects are the same type? and why are you testing the result of the static method instead of just the type? using [datetime] instead of [datetime]::today() works without any errors ... [grin]
    – Lee_Dailey
    Oct 14 at 2:29
  • doesn't seem to be working for me though PS C:\Users\juraj> Get-ChildItem Cert:\localMachine\My | Where-Object { $_.NotBefore -is [DateTime]::Today() } Method invocation failed because [System.DateTime] does not contain a method named 'Today'.
    – JurajB
    Oct 14 at 4:24
  • REMOVE the silly static method from your [datetime] section. _just use the type ... the -is operator checks a TYPE, not a static method. [grin]
    – Lee_Dailey
    Oct 14 at 4:45

I've worked it out - I converted string into [datetime] and then use it as a filter

$string=[Datetime]::ParseExact($string, 'dd/MM/yyyy', $null)
Get-ChildItem -Recurse Cert:\localMachine\My | Where { $_.NotBefore -lt $string  } | Remove-Item
  • 1
    excellent! [grin] that not only works ... it makes your intent clear. the other code was using -is in ways that made the intent unclear to me.
    – Lee_Dailey
    Oct 14 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.