Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Wednesday, December 22, 2010

How to tell how long it has been since a computer logged in with PowerShell

This is an easy one liner in PowerShell.

Open PowerShell V2.

Once open, we need to access the Active Directory objects by typing Import-Module ActiveDirectory.

Now Type Get-adcomputer –filter * -properties lastlogondate | Where {$_.LastLogonDate –le [DateTime]::Now.AddDays(-7)}

We first use the Get-ADCopmuter cmdlet to access the computer objects in Active Directory. Setting –filter * allows us to work with all the computer objects. Next we added the –properties LastLogonDate. This is done because that attribute is normally now returned with the object. Second, we piped the output of the first command to the Where cmdlet. The $_.LastLogonDate variable looks at each input one at a time and grabs the LastLogonDate attribute for analysis. We then compare it to [DateTime]::Now.AddDays(-7) This command gets the current date/time from the host and subtracts 7 days from it. We then use the –le comparision operator (Less than or equal to) to determine if the date in Active Directory for the computer object is more than 7 days old.

No comments: