retrieve computer names admin account logged on through AD - powershell

How would retrieve computer names and their IP addresses in Active Directory which are logged into by an admin account?
I can retrieve local admin accounts with my script below:
function get-localadministrators {
param ([string]$computername=$env:computername)
$computername = $computername.toupper()
$ADMINS = get-wmiobject -computername $computername -query "select * from win32_groupuser where GroupComponent=""Win32_Group.Domain='$computername',Name='administrators'""" | % {$_.partcomponent}
foreach ($ADMIN in $ADMINS) {
$admin = $admin.replace("$computernamerootcimv2:Win32_UserAccount.Domain=","") # trims the results for a user
$admin = $admin.replace("$computernamerootcimv2:Win32_Group.Domain=","") # trims the results for a group
$admin = $admin.replace('",Name="',"")
$admin = $admin.REPLACE("""","")#strips the last "
$objOutput = New-Object PSObject -Property #{
Machinename = $computername
Fullname = ($admin)
DomainName =$admin.split("")[0]
UserName = $admin.split("")[1]
}#end object
$objreport+=#($objoutput)
}#end for
return $objreport
}#end function
but what I want is to return all instances of Administrator logged on to Computers. Is this possible or is there anything that would return similar results?

You are not going to be able to do this with AD alone.
How many computers are we talking here? Nevertheless, i would make use of the eventlog. Each logon-event is stored and has the SID of the user that logs on (or triggers the event). Event 7001 (logon) is what you are looking for.
You could retrieve these events in een XML format. This XML contains the SID of the user that has triggered the event. You can either use a .NET translation function to convert it into a SamAccountName OR you can just retrieve all SID's from AD and compare them that way (so maybe make use of a hasbtable).
I have written a script some time ago that uses a lot of these techniques.
It was meant to see when a user has logged on and off AND locked and unlocked their computer. You can find a blog-post about it here:
https://cookiecrumbles.github.io/GetLogonEventViewer/
That blogpost also references the github where you can find the script i made.
With some tweaking, you could make it into a tool that you need.

Related

Security Group changes - Task

I'm currently auditing security events 4728 and 4729 via powershell in order to check group policy changes in a specific domain controller.
The main idea is to check anomalies between a default AD group policy(a "given configuration", for the company group) and the one that changed(from the new snapshot) at the end of the week.
How could I spot differences beetween these two outputs?
I'd use Get-WinEvent -LogName Security, but we can discuss it.
For Changes I refer to these https://learn.microsoft.com/en-us/windows/security/threat-protection/auditing/audit-security-group-management
(4728,4729 for instance)
I'm looking for a situation like this: an administrator add a user to a security group because the latter has to access a specific file for a short period of time.
Then the admin somehow forgets to restore the original user's configuration policy.
This generates an anomaly, considering the default AD Group Policy.
I have to spot this change from the output.
Now I've wrapped up my rudimentary explination, is there anything you can think of to help with my problem?
Thanks in advance
The basic command you're looking for would be like this:
$StartDate = (Get-Date).AddDays(-1)
Get-WinEvent -FilterHashtable #{ LogName='Security'; Id=4728, 4729; StartTime=$StartDate }
In a script it would be something like this:
$StartDate = (Get-Date).AddDays(-1)
$Results = Get-WinEvent -FilterHashtable #{ LogName='Security'; Id=4728, 4729; StartTime=$StartDate }
if ( $Results )
{
# Send e-mail or something here
}
If you want more complex queries you might format it differently.
$DaysInThePast = 1
$Hash = #{
LogName = 'Security'
Id = 4728, 4729
StartTime = (Get-Date).AddDays(-$DaysInThePast)
}
Get-WinEvent -FilterHashtable $Hash

Export-Csv MIM FIM PowerShell Issue

I was asked to retrieve a .csv list with all users that registered to the FIM portal. I did some searching until I stumbled accross this script:
set-variable -name URI -value "http://localhost:5725/resourcemanagementservice' " -option constant
set-variable -name CSV -value "RegistredResetPassUsers.csv" -option constant
clear
If(#(Get-PSSnapin | Where-Object {$_.Name -eq "FIMAutomation"} ).count -eq 0) {Add-PSSnapin FIMAutomation}
$WFDFilter = "/WorkflowDefinition[DisplayName='Password Reset AuthN Workflow']"
$curObjectWFD = export-fimconfig -uri $URI –onlyBaseResources -customconfig ($WFDFilter) -ErrorVariable Err -ErrorAction SilentlyContinue
$WFDObjectID = (($curObjectWFD.ResourceManagementObject.ResourceManagementAttributes | Where-Object {$_.AttributeName -eq "ObjectID"}).value).split(":")[2]
$Filter = "/Person[AuthNWFRegistered = '$WFDObjectID']"
$curObject = export-fimconfig -uri $URI –onlyBaseResources -customconfig ($Filter) -ErrorVariable Err -ErrorAction SilentlyContinue
[array]$users = $null
foreach($Object in $curObject)
{
$ResetPass = New-Object PSObject
$UserDisplayName = (($Object.ResourceManagementObject.ResourceManagementAttributes | Where-Object {$_.AttributeName -eq "DisplayName"}).Value)
$ResetPass | Add-Member NoteProperty "DisplayName" $UserDisplayName
$Users += $ResetPass
}
$users | export-csv -path $CSV
The script works without errors except that the actual list that it exports only contains my display name. I've been trying to figure out why its not exporting the complete list of all users and only shows my name, but I haven't been able to figure it out so I was wondering if any one could help me shed some light into this issue.
Thanks again for any help you guys can provide!
No experience with this snapin/product, but seeing as the code fundamentally works (it returns your object) this could be a permissions issue. You may not be able to read the other user objects, so they're not being exposed to you.
If you can view them in a UI console of some kind, then check for separate permissions related to API actions, and ensure you have access that way.
Another course of action may be to run the code line by line and see what results you receive from each line, to make sure you get what you're expecting.
Try replacing:
[array]$users = $null
With:
$users = #()
This is likely due to permission setup.
By default you have a permissions to see your own attributes.
There is likely some Management Policy Rule setup so user accounts in a specific Set can read AuthNWFRegistered attribute of other users to support for troubleshooting and customer support.
You will need to use one of the options:
Add the account used for this script into the Set that delegates out this Read permission already
or
Create a separate MPR for this particular reporting (this is what I would recommend) that Grants permissions for a specific user account to read AuthNWFRegistered attribute.
Also make sure there is really only one Workflow that is associated with user registration. If there are multiple, you'd want to target Set with all register Workflows in your XPath filter instead of particular Workflow name.
On a separate note - while FIMAutomation is sometimes necessary snapin to use with standard tooling, for your custom work I strongly suggest to use Lithnet's LithnetRMA PowerShell module (https://github.com/lithnet/resourcemanagement-powershell).
You will be much more productive with it and most of the operations will be without boilerplate code FIMAutomation needs. This will be your code using LithnetRMA.
Set-ResourceManagementClient -BaseAddress 'http://localhost:5725/resourcemanagementservice'
$scope = Search-Resources -XPath "/Person[AuthNWFRegistered = /WorkflowDefinition[DisplayName='Password Reset AuthN Workflow']]" -ExpectedObjectType Person
$scope | select DisplayName | Export-Csv 'RegistredResetPassUsers.csv' -Encoding Unicode

Finding a User on one of many domains

I am trying to get a script running but I keep running across the same issue, I have domains A, B, and C all in the same forest; but when I try to do simple commands such as
Disable-ADAccount -Identity $User
I am not able to get it to complete because it can't find the user in Domain B, which the user is in Domain A.
So the question, is there a way to get a script to check all domains (A, B, C) for "User1" and preform the disable action on them. (Other than setting the Switch)
-server
I ran into this issue recently, and ended up writing a function to get a user's ADUser object. You could use that object to disable the user easily enough.
Function Get-DomainUser{
Param([String]$Alias)
BEGIN{$GCs = Get-ADForest|select -expand GlobalCatalogs|?{($_ -match "^(.*?)\.(.+?)$")}|%{[pscustomobject]#{'Server' = $matches[1];'Region' = $matches[2];'FQDN' = $_}}|group region|%{$_.group|select -first 1}
}
PROCESS{
$DomUser = Get-ADUser -Filter {samAccountName -eq $Alias} -Prop DisplayName
If(([string]::IsNullOrEmpty($DomUser.Name))){
ForEach($GC in $GCs){
$DomUser = Get-ADUser -Filter {samAccountName -eq $Alias} -Server $GC.FQDN -Prop DisplayName
If(!([string]::IsNullOrEmpty($DomUser.Name))){Break}
}
}
$DomUser
}
}
This gets a list of global catalog servers, groups them by sites, then gets only 1 server per site. Then it tries to get the user, and if it fails for the current user then it tries each site until it finds the user.

Searching AD Groups attached to specified Server

I'm looking to use powershell, specify a server hostname, and have it display all the AD Groups that have access to that server. From there I'll dig into the groups eventually getting the usernames and storing them in a csv file.
So far I have the code to get the DN of the server -
Get-adcomputer HOSTNAME | select DistinguishedName
Along with having the code to get the eventual usernames and store them in a csv -
$groups= GROUPS
$selectgroups=$groups |Get-Adgroup
$selectgroups |get-adgroupmember -Recursive | Select samaccountname |
Export-csv -path C:\Groups\Members.csv -NoTypeInformation
My problem is I can't figure out how to get powershell to query what groups are on the server I specify. Is this possible or will I have to look at another way of doing this?
Thanks.
Not sure you know exactly what you're looking for. There's no way to tell which AD groups have been granted access to a node via AD. The only thing you can do is look on the local node for AD groups, but there's a lot of places you could want/need to look as Frode F. mentioned already. A common theme would be which AD groups have been added to LOCAL groups on the node in question.
You could use WMI or the ADSI adapter for this information. An ADSI example to get all members of the 'Administrators' local group for server 'NODE123':
$server = "NODE123"
$arrGroupMembers=#()
$Group = "Administrators"
$ADSIComputer = [ADSI]("WinNT://" + $server + ",computer")
$ADSIGroup = $ADSIcomputer.psbase.children.find($Group)
$ADSIMembers= $ADSIGroup.psbase.invoke("Members")
foreach ($member in $ADSIMembers) {
$MemberClass = $member.GetType().InvokeMember("Class", 'GetProperty', $Null, $member, $Null)
if ($memberClass -eq "Group") {
$MemberName = $member.GetType().InvokeMember("Name", 'GetProperty', $Null, $member, $Null)
$arrGroupMembers+=$MemberName
}
}
With the array return above, you now have all groups that have access to NODE123 via being added to the local Administrators group. Maybe this example helps you.

returning and referencing remote powershell variable results

I'm very new to powershell so looking some assistance. I am trying to run remote powershell script to check health of or VDI enviroment using Citrix Commandlets. (I am implementing the script on Microsoft orchestrator .Net Activity). So I have the following code:
#2012 VDI Desktop check
$vdims = "MyCitrixPowershellSDKServer"
function vdidesktopcheck
{
asnp Citrix*
$result = Get-BrokerDesktop -InMaintenanceMode $True -DesktopGroupName Unidesk
$result
}
$output = invoke-command -computer $vdims -scriptblock ${function:vdidesktopcheck}
$machinename = $output.machinename
$machinename
$state = $output.RegistrationState
$state
So when I use orchestrator to expose the variables $machinename, $state - I get the 'last' result from the involked Get-BrokerDesktop query. However Get-Brokerdesktop query may have multiple machines returned so I am hoping to be able to reference each of the machines that match the query output. Thats the basic requirement - what I am hoping to be able to do is further refine the basic Get-BrokerDesktop query to be able to count the number on machines output to say > 3 (ie more than 3 machines in MaintMode is unacceptable) and also check that the MachineName property is not equal to a particular value, ie the 3 test machine names in the environment which may be expected to be in MaintenanceMode.
Hope this makes sense, if not I'll try and elaborate. Any help much appreciated!!
One of the limitations of Orchestrator is that you can only pass strings across the data bus, and you need to pass an array of objects. You need to serialize the object array to a string. One way to do that is to convert the array to json, then use convertfrom-json when you get it back to get an object array to work with.
Don't have a SCORCH server handy to test with, so this isn't tested at all.
$vdims = "MyCitrixPowershellSDKServer"
function vdidesktopcheck
{
asnp Citrix*
$result = Get-BrokerDesktop -InMaintenanceMode $True -DesktopGroupName Unidesk
$result
}
$output = invoke-command -computer $vdims -scriptblock ${function:vdidesktopcheck} |
select machinename,RegistrationState | ConvertTo-Json
$Output