Forum Discussion
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)
- TJCooper440Copper ContributorIt works in Powershell 5
- LainRobertsonSilver Contributor
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
- TJCooper440Copper ContributorI 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_AndersonCopper Contributor
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_AndersonCopper 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))
- TJCooper440Copper ContributorI will try that, but I dont think that is the issue. The $time is correct. It simply wont work when doing the comparison.
- Vern_AndersonCopper Contributor
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}
- TJCooper440Copper Contributor
This is the original code. I added the $_. before lastlogintimestamp.
Active Directory: How to Find Inactive Computers in | Microsoft Learn$DaysInactive = 90 $time = (Get-Date).Adddays(-($DaysInactive)) Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -ResultPageSize 2000 -resultSetSize $null -Properties Name, OperatingSystem, SamAccountName, DistinguishedName