Forum Discussion

TJCooper440's avatar
TJCooper440
Copper Contributor
Oct 16, 2024

Powershell 7 - $time is not defined - Script from Microsoft

I get the error "Get-ADComputer: Variable: 'time' found in expression: $time is not defined.". The script is straight from Microsoft and $time is populated with a date/time. It seems very simple, I don't know what is going wrong.

 

 

$DaysInactive = 90
$time = (Get-Date).Adddays(-($DaysInactive))
Get-ADComputer -searchbase "OU=SC,OU=Servers,DC=WSDOT,DC=LOC" -Filter {LastLogonTimeStamp -lt $time} -ResultPageSize 2000 -resultSetSize $null -Properties Name, OperatingSystem, SamAccountName, DistinguishedName

(edited: correct code to reflect what was being tested) 

    • LainRobertson's avatar
      LainRobertson
      Silver Contributor

      TJCooper440 

       

      Hi, Theron.

       

      I've copied and pasted the first two lines of your code verbatim into PowerShell and am not seeing an issue.

       

       

      Cheers,

      Lain

      • TJCooper440's avatar
        TJCooper440
        Copper Contributor
        I do not get an error then either. Its when it does the comparison with the lastlogindate it is generating an error. It works in Powershell 5.
  • Vern_Anderson's avatar
    Vern_Anderson
    Copper Contributor

    TJCooper440 

    Since it's hard coded in the script anyway why even set the variable to 90? Just set negative 90 right in the parenthesis!

     

    $time = (Get-Date).Adddays(-90)
    Get-ADComputer -searchbase "OU=SC,OU=Servers,DC=WSDOT,DC=LOC" -Filter {$_.LastLogonTimeStamp -lt $time} -ResultPageSize 2000 -resultSetSize $null -Properties Name, OperatingSystem, SamAccountName, DistinguishedName
    • Vern_Anderson's avatar
      Vern_Anderson
      Copper Contributor

      The only other suggestion I would have if it has to be a variable, you could try adding one more dollar sign in front of the parenthesis like so. . .

       

      $time = (Get-Date).Adddays(-$($DaysInactive))
    • TJCooper440's avatar
      TJCooper440
      Copper Contributor
      I will try that, but I dont think that is the issue. The $time is correct. It simply wont work when doing the comparison.
      • Vern_Anderson's avatar
        Vern_Anderson
        Copper Contributor

        TJCooper440 

        I just now noticed that you have the $_.LastLogonTimeStamp
        To my knowledge the $_ indicates an object that was "piped" in I do not see where you piped any objects in.
        of course I do not use AD CMDLETs as often as some others but this syntax seems to be the issue here.

        Get-ADComputer -Filter * | Where-Object {$_.LastLogonTimeStamp -lt [DateTime]$Time}

        You could try this but when I query my AD computers that property is NULL on every computer, or I may not have rights to see it.

        If you do this command does it return any computer objects??

        Get-ADComputer -Filter * | Where-Object {$_.LastLogonTimeStamp}

Resources