How to filter out which users are allowed to log in to a computer? - powershell

I am needing to parse through user information to find which computers a specific user has access to, and then filter that out to generate txt docs for each computer listing the allowed users for that machine. However, my script isn't returning expected results and is creating incomplete lists.
Get-Content c:\temp\computers.txt | ForEach-Object {
$computername = $_
Get-ADUser -Filter "LogonWorkstations -like '*$computername'" -Properties LogonWorkstations |
Format-Table SamAccountName, Enabled |
Out-File -FilePath c:\temp\Accounts\"$computername-$fileDate".txt
}
I am fairly certain the issue lies in my filtering, because some of the files are returning info, however only ones where the username matches the computer name in some regard. Rather than listing users whose "LogonWorkstation" includes said computer, which is what I am looking to do. (If I pull a user's "LogonWorkstation" separately, that information is correct.)

I believe the issue is that the logonworkstations property stores the list of computers as a string rather than a collection. Since the -Filter parameter has limited operators, you will need to use -like in order to introduce wildcards. Then you can use whatever method to build your computer name string to include surrounding asterisks.
Get-Content c:\temp\computers.txt |
ForEach-Object {
Get-ADUser -Filter "LogonWorkstations -like '*$_*'" -Properties LogonWorkstations |
Format-Table SamAccountName, Enabled |
Out-File -FilePath c:\temp\Accounts\"$_-$fileDate".txt
}

Related

Get-ADComputer to return a different property than queried?

I am using Get-ADComputer to search through my domain for a specific string in the Location property. However, when I find it, I want to return the Name property the string was found in.
My company is using Powershell version 5.1 if that makes a difference.
I've already tried piping Name after "select-string -Pattern 'example'" but it simply returns nothing, I assume it thinks I'm looking for the property within Location rather than the Get-ADComputer result. The answer will probably be someone telling me to store the whole Get-ADComputer as a variable, but I'm not sure what the data limit on Powershell variables are, and it seems I would be parsing through quite a lot of data.
Get-ADComputer -properties Location -SearchBase "OU=E, DC=M" -filter 'Name -like "*"' | select Location | select-string -pattern "example"
My current result is the entire Location property, but my desired result is the Name property while searching for the location. It would be even better if I could return both.
If you are looking for the string example within location, you can filter on location and then output the name.
Get-ADComputer -SearchBase "OU=E, DC=M" -Filter "location -like '*example*'" | Select-Object Name
If you are looking for the string example within Name, you can filter on Name and still output the name.
Get-ADComputer -SearchBase "OU=E, DC=M" -Filter "Name -like '*example*'" | Select-Object Name
If you want to output more properties including location and Name, you will need to add the -properties switch to handle location.
Get-ADComputer -Properties location -SearchBase "OU=E, DC=M" -Filter "Name -like '*example*'" | Select-Object Name,location
If you are looking to find string example within any property that outputs by default from the Get-ADComputer command, then you will need something like the following:
Get-ADComputer -Properties location -SearchBase "OU=E, DC=M" -Filter * | Where-Object { $_ | Out-String | Select-String -pattern "example"}
Explanation:
Select-Object will output a custom object with the properties that you have selected. The -Filter on the AD commands has limited operators available. If you are looking for a simple string, know what property contains the string, but don't know where the string exists within the string, use the -like operator. The * characters are for wildcards. -Filter is almost always faster than piping into something else, so you should use it if you can.
The Where-Object { $_ } processes the current object ($_) in the pipeline, which includes all of the properties piped into the command. If you only want to compare a single property, then $_ should become $_.propertyname.

Compare AD users from CSV to a specific OU

I have a CSV list of usernames from all over my domain, and I'm trying to compare the list against a specific OU and send the matches to another file. I'm brand new to powershell, so after a good amount of research and comparing with other scripts I came up with this:
$users = Import-csv C:\Users\me\Desktop\'RSA.csv'
$(ForEach ($user in $users)
{
Get-AdUser -identity $user -SearchBase "ou=Sub,ou=Root,dc=My,dc=Domain,dc=Name" -Filter *
}) |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
When I run this I get the error "Get-ADUser : Cannot validate argument on parameter 'Identity'. The Identity property on the argument
is null or empty." If I run without the -identity $user it just pulls everything. Any suggestions on how to make this work?
When you are calling Get-ADUser rather than giving it a string with just the user name you are passing in an object with a property called username. You could use Select-Object -ExpandProperty Username or reference the just property.
Import-Csv 'C:\Users\me\Desktop\RSA.csv' |
Where-Object {(!([string]::IsNullorWhiteSpace($_.UserName)))} |
ForEach-Object {
Get-ADUser -Identity $_.UserName
} |
Select-Object SamAccountName |
Export-CSV -Path C:\Users\me\Downloads\test\output.csv -NoTypeInformation
Notes: Changed to a ForEach-Object loop for readability since it looked like you where trying to mostly use the pipeline. Also added a test to skip blank lines or usernames that are whitespace/empty string. Removed the SearchBase and Filter since you are looking up based on identity can't use those in the command. As there isn't a parameter set that allows you to use all of them. Get-Help Get-ADUser shows the available parameter sets.

I have a .csv with thousands of emails, and I need to use Active Directory to find the state of a particular, custom variable, using powershell

I'm new and don't know enough about powershell.
I've got a .csv that is nothing but "EMAILS" for the header and some 6000 emails under it. (email1#company, email2#company, etc.)
I need to find the state of a particular, custom property for each one.
Individually, I know that I can run
Get-ADUser -Filter {mail -eq 'email#company'} -properties customproperty
in order to find one particular user's state.
I have been hitting my head against a wall trying to make it work with import-csv and export-csv, but I keep getting red all over my console.
Can someone point me an to example where import-csv and export-csv are used properly, with a command run against the contents?
Here's what I would do.
First, fetch all users that have email addresses in AD, and save them into a hashtable. This will make lookups absurdly faster and place less overall load on your domain controller. If you've got 100,000 user accounts it may not be the best option, but I expect that it will be in general.
$ADUsers = #{};
Get-ADUser -Filter "mail -like '*'" -Properties mail, customproperty | ForEach-Object {
$ADUsers.Add($_.mail, $_.customproperty);
}
Now you import the CSV and do lookup using a calculated property with Select-Object, and export it back out.
Import-Csv -Path $InputFile | Select-Object -Property emails, #{n='customproperty';e={$ADUsers[$_.emails]}} | Export-Csv -Path $OutputFile -NoTypeInformation;
So without seeing the code of what you posted, where I think you will run problems is with how interaction of two things.
The first will be that when you use the Import-CSV cmdlet. You will receive an array of objects with a property for each column and not an array of strings.
This is ties into the second part of the issue which is the sensitivity of the AD module filter. But the short answer is don't use {} inside the filter because it will break if you use {mail -eq $ImportedCSV.EMAILS}.
mklement0 has a wonderful answer that goes into the details. But a simple rule of thumb is "double quote outer, single quote" inner.
So you could expand the EMAILS property either with Select-Object -ExpandProperty EMAILS to have an array which works inside {} or you could use "mail -eq '$ImportedCSV.EMAILS'".
Here is an example with both the expansion and using the "property -eq '$variable'" style filter:
Import-CSV C:\Example\Path.csv |
Select-Object -ExpandProperty EMAILS |
ForEach-Object {
Get-ADUser -Filter "mail -eq '$_'" -Properties customproperty
} |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
Please use below code
$csvInput = Import-CSV C:\Example\test.csv
Foreach ($line in $csvinput) {
Get-ADUser -Filter {mail -eq $line.mail} -Properties mail, customproperty |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
}

Powershell script to display all Users in a Group AD

I have created the below
Get-ADGroup -Filter * -SearchBase "DC=Domain,dc=.com" -properties name, members |
Select-Object *,#{Name='Member';Expression={$_.Members -replace '^CN=([^,]+).+$','$1'}} |
FT Name, Member -Autosize |
out-file c:\text.txt
Ignore Domain and .com I have them populated with my relevant information, but for sake of here removed them.
When I run this it returns what I'm after but when looking at the members within the group they all end with ... and don't show all the members
There are a few things to correct. Let's look at them in order. The actual AD query can be simplified: you only need to specify 'Members' as an additional property to retrieve as 'Name' is brought back by default:
Get-ADGroup -Filter * -SearchBase "DC=Domain,dc=.com" -properties members
Given that you only want to output two properties ('Name' and your custom one 'Member'), use your select to retrieve only the ones you want:
Select-Object Name ,#{Name='Member';Expression={$_.Members -replace '^CN=([^,]+).+$','$1'}}
Remove the Format-Table: we have already limited the selection in the previous command. Format cmdlets are designed to format the output to the console window and best practice dictates that they should only be used for that purpose and that they should always be the last element of a pipeline.
Piping all of that to Export-Csv will then produce what you want:
Export-Csv -NoTypeInformation -Path C:\text.csv
This one did the trick for me
Get-ADGroupMember -Identity Administrators | Select-Object name, objectClass,distinguishedName | Export-CSV -Path “adgroupmembers.csv”
I got this here.
https://www.lepide.com/how-to/export-members-of-a-particular-ad-group-using-poweshell.html#:~:text=The%20PowerShell%20Get%2DADGroupMember%20cmdlet,group%20you%20want%20to%20use.

Powershell pipe variables into get-user command

I am trying to pipe a list of email addresses into a get-user command in powershell
$email = get-content -path "c:\temp\file.csv" get-user -indentity $email | select-object userprincipalname,department,phone,name | format-table | out-file c:\temp\file.txt
Welcome to SO.
Lets see... where to start
Email Address is not one of the value recognized for Identity
It is spelled -identity
Don't use Format-table for object output.
Department is not one of the default values returned.
There is no AD attribute just called phone
It's Get-Aduser not get-user
Don't know if it was just a copy paste accident but you have multiple lines as one.
-Identity expects one value. Not an array of names.
Knowing that lets see if we can take a stab at what you were trying to do. Assuming that your file "c:\temp\file.csv" only contained addresses with no header (since that is how you were treating it.)
Get-Content c:\temp\file.csv | ForEach-Object{
Get-ADUser -Filter "emailaddress -eq '$_'" -Properties department,OfficePhone
} | Select-Object UserPrincipalName,Department,OfficePhone,Name | Export-CSV C:\temp\outputfile.csv -NoTypeInformation
There is no error correction here so you might need to look into an -ErrorAction try/catch combination. I encourage you to look that up on your own.