loop query through all DCs

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 9 years and 3 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
daviesg6
Posts: 49
Last visit: Tue Nov 25, 2014 1:23 pm

loop query through all DCs

Post by daviesg6 »

So I have a script that provides account info, all very nice and helpful for support staff. However, I need to provide accurate information relating to the last time a user logged on. I am using lastlogontimestamp and converting it to a readable format, but it does not provide the correct information very often because the attribute is not replicated across the DCs, so it only provides the information from the viewpoint of the DC providing the answer. How do I loop this through the 5 DCs we have in a primal forms GUI?
The current script is below, the variables are:

$results = Output window
$EntryBox = text input box used to provide the account name being queried
PowerShell Code
Double-click the code block to select all.
$results.Text=Get-ADUser -Filter "DisplayName -eq '$($EntryBox.text)'" -Properties DisplayName, sAMAccountName, mail, lastlogontimestamp, extensionattribute5, PasswordLastSet, PasswordExpired, PasswordNeverExpires, buMemberOf, msExchOmaAdminWirelessEnable | select givenName, surname, DisplayName, sAMAccountName, mail, @{n='LastLogontimestamp';e={[DateTime]::FromFileTime($_.LastLogontimestamp)}}, extensionattribute5, PasswordLastSet, PasswordExpired, PasswordNeverExpires, buMemberOf, msExchOmaAdminWirelessEnable | Out-String
    $results.Focus()
I know I need to create a variable for the DCs, I just don't get where to create this or how to make the query for the lastlogontimestamp loop through these, nor do I understand how to make it display the newest of these events as the result
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: loop query through all DCs

Post by jvierra »

You just loop through all of the DCs and get the time. Compare until you get the latest time.

Some background:

http://oxfordsbsguy.com/2014/04/28/powe ... te-part-1/
User avatar
daviesg6
Posts: 49
Last visit: Tue Nov 25, 2014 1:23 pm

Re: loop query through all DCs

Post by daviesg6 »

I get I have to loop it through, I tried a few things and either got errors running the script or got lastlogon date as 1/1/1600, what I'm looking for is a pointer to how I do this within the script I have already, where do I create the list of DCs and how do I loop the lastlogontimestamp query through the list of DCs
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: loop query through all DCs

Post by jvierra »

PowerShell Code
Double-click the code block to select all.
$userid='samname'
$logons=@()
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers |
    ForEach{
        $logonInt=(Get-Aduser $userid -computer $_.Name -properties lastlogon).lastlogon
        $logons+=[datetime]::FromFileTime($logonInt)
    }

$newestLogon=($logons|Measure-Object -Max).Maximum
User avatar
daviesg6
Posts: 49
Last visit: Tue Nov 25, 2014 1:23 pm

Re: loop query through all DCs

Post by daviesg6 »

I copied the code block into ISE and tried to run it. I know the $userid value is not valid so expected an error, but it gave me this:
Get-ADUser : A parameter cannot be found that matches parameter name 'computer'.
At line:5 char:39
+ $logonInt=(Get-Aduser $userid -computer $_.Name -properties lastlogontim ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Get-ADUser : A parameter cannot be found that matches parameter name 'computer'.
At line:5 char:39
+ $logonInt=(Get-Aduser $userid -computer $_.Name -properties lastlogontim ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Get-ADUser : A parameter cannot be found that matches parameter name 'computer'.
At line:5 char:39
+ $logonInt=(Get-Aduser $userid -computer $_.Name -properties lastlogontim ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Get-ADUser : A parameter cannot be found that matches parameter name 'computer'.
At line:5 char:39
+ $logonInt=(Get-Aduser $userid -computer $_.Name -properties lastlogontim ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Get-ADUser : A parameter cannot be found that matches parameter name 'computer'.
At line:5 char:39
+ $logonInt=(Get-Aduser $userid -computer $_.Name -properties lastlogontim ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADUser

I'm not a scripting expert, hence asking for help, so I'm lost when it comes to fixing this, and even more so when it comes to integrating that into the existing script I already have. Just telling someone they need to do something they have already said they need to do but don't know how doesn't help, neither does posting a block of code that has no context or any kind of comments giving a clue what to do with it.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: loop query through all DCs

Post by jvierra »

Sorry the parameter should be -server.
User avatar
daviesg6
Posts: 49
Last visit: Tue Nov 25, 2014 1:23 pm

Re: loop query through all DCs

Post by daviesg6 »

thanks, got it working as a standalone scriptnow
User avatar
Cliving
Posts: 57
Last visit: Tue Apr 25, 2023 12:37 pm

Re: loop query through all DCs

Post by Cliving »

Alternatively, you can querry DC's in a particular site. Some organizations might have multiple sites and you might not want or need to query all DC's in your organization. For example, you might not have a need to query DC's in a DR site that normal domain users never authenticate against. The following is a way to query all DC's in the current site you're connected to. It might not be as elegant as the previous solution, but it might help with similar situations.
PowerShell Code
Double-click the code block to select all.
try {
		#Counter is zeroed out to start with
		$LastLogonTime = 0
		#Gets the object for the DC that the admin is currently logged onto
		$CurrentDC = Get-ADDomainController -ErrorAction Stop
		#Gets a list of all DC's in the admin's current AD site
		$DCs = Get-ADDomainController -Filter { site -eq $CurrentDC.site } -ErrorAction Stop
		#Loops through all DC's in the current site
		foreach ($DC in $DCs) {
			#Tests whether each DC is currently online to prevent longer timeouts if the DC is offline
			if (Test-Connection -ComputerName $DC.hostname -Count 1 -Quiet) {
				#Gets the lastlogon time from the DC currently in the loop
				$ThisLogon = Get-ADUser -Identity $global:CurrentUser.SamAccountName -Server $DC.hostname -Properties lastlogon -ErrorAction Stop
				#If the lastlogon time is more recent that what was previously known, the most recent time is the one used
				if ($ThisLogon.lastlogon -gt $LastLogonTime) {
					$LastLogonTime = $ThisLogon.lastlogon
					#Just like with lastlogon time, the DC in which the user last logged on is saved to a global variable to be used if needed
					#This command is what gets the value for the button click event for last logon server
					$Global:LastLogonServer = $DC.hostname
				}
			}
		}
		#formats the lastlogon time to a readable date/time format
		$Time = [DateTime]::FromFileTime($LastLogonTime)
		#returns the date/time from the function
		return $Time
	}
	catch {
		[System.Windows.Forms.MessageBox]::Show("An error has occured querying 'Last Logon Time' for $($global:CurrentUser.samAccountName). Please contact Systems Support.", "Status", 0)
	}
This function is specific to a project I was working on but can simply be modified to suit your needs.
This topic is 9 years and 3 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked