In Powershell how can I remove the first x number of characters from Get-ADUser results? - windows

I have a list of results from Get-ADUser giving me all users in an OU. The format of the output username is '-prefix-username'. I need to remove the 7 character '-prefix-' and then conduct another Get-ADUser lookup against the remaining 'username' portions. The issue I'm finding is that if I run just the second Get-ADUser lookup where I set $User as just one specific '-prefix-username' it works fine but when I try to process a list I either get an error where there seems to be space after the trimmed username (txt format list - Get-ADUser : Cannot find an object with identity: 'user ' under:) or the username includes a " that I can't remove from the end of the username (csv format list - Get-ADUser : Cannot find an object with identity: 'user"').
So far I have:
get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 |
Select SAMAccountName |
Out-File C:\Temp\UserList.txt
$UserList = (Get-Content C:\Temp\UserList.txt)
$StandardUsers = ForEach($User in $UserList) {
Write-Host "Now checking $User"
Get-ADUser $User.Substring(7) -Properties * |
Select-object DisplayName, UserPrincipalName, Mail, Manager,EmployeeID
}
$StandardUsers | Out-File -FilePath C:\Temp\StandardUserList.txt

First thing to mention is that if you create the list using Select -ExpandProperty SAMAccountName, you would only get SamAccountnames in the file.
Having said that, why bother with an 'in-between' file at all and simply do:
# By default, Get-ADUser returns these properties:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
# Only ask for properties that are not already in this list.
Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 -Properties DisplayName, EmailAddress, Manager, EmployeeId |
Select-Object DisplayName, UserPrincipalName, EmailAddress, Manager,EmployeeID |
Set-Content -Path 'C:\Temp\StandardUserList.txt'

You are likely having issues with saving it to a file (where it gets formatted) and then reading it back in. The formatting could be adding " and reading a newline (which you think is a space) character. If you really need to save it then do the following (else just hook up the pipelines):
$userList = Get-ADUser -Filter * -SearchBase 'OU=SomeOU' -SearchScope 2 |
Select-Object SAMAccountName
$userList |
Out-File C:\Temp\UserList.txt
$standardUsers = $userList |
Select-Object -ExpandProperty SAMAccountName -PipelineVariable user |
ForEach-Object {
Write-Host "Now checking $user"
$userWithoutPrefix = ($user -Replace '^-prefix-','') -Replace '(\w|\n)$','' # to use a more advanced version of the suggestion by #Avshalom
Get-ADUser $userWithoutPrefix -Properties * | Write-Output
} |
Select-Object DisplayName, UserPrincipalName, Mail, Manager, EmployeeID
$standardUsers | Out-File -FilePath C:\Temp\StandardUserList.txt

Related

AD Users Script correction

Can anyone please correct?
Individual runs of user1 and user 2 running good and appending results
(get-aduser -Identity user1 -Properties memberof | select -expand memberof | get-adgroup) |
select Name, groupscope | Out-File -Append c:\scripts\resultsusersad.txt
(get-aduser -Identity user2 -Properties memberof | select -expand memberof | get-adgroup) |
select Name, groupscope | Out-File -Append c:\scripts\resultsusersad.txt
When I tried to save both users in a text file and used for loop I am getting error.
This is what I did, given below (Update):
$file = Get-Content -path "c:\scripts\usersad.txt"
foreach ($i in $file)
{
(get-aduser -Identity $($i) -Properties memberof | select -expand memberof | get-adgroup) | select Name, groupscope | Add-Content -Path c:\scripts\resultsusersad.txt
}
Please correct where I am doing wrong.
I always have trouble with out-file.
What I would do is:
Either create a new file in the script, or have one already created and waiting.
Variablize the output. Something like
$Var1 = #(user1 -Properties memberof | select -expand memberof | get-adgroup) | select Name, groupscope)
Use 'Add-Content' to write to the file
Add-Content -Path .\myfile.txt -Value $Var1
I it will append the string as a new line right under the previous one. I use to use a similar method to build CSVs from grabbing data from AD.

Get-AD Computer not match text file content

I want to get a list of all ad computers excluding the servers that are in a text file. Here's my code:-
$excludedServers = (Get-Content
"C:\Users\testuser\Documents\RdpDisconnectedSessions\ExcludedServers.txt").name #| Sort-Object
Get-ADComputer -Filter * | Where { $_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notmatch $excludedServers } | Select-Object Name
Any advise please ?
First, Get-Content is not going to bring back objects so the .name portion is not going to work. If it's just a list of computernames, then simply change it to.
$excludedServers = Get-Content "C:\Users\testuser\Documents\RdpDisconnectedSessions\ExcludedServers.txt"
If it's a CSV with a name column, then you can do it a few ways. Sticking with the format you had this would work
$excludedServers = (Import-Csv "C:\Users\testuser\Documents\RdpDisconnectedSessions\ExcludedServers.txt").name
Now that you have your list of names, you can filter like this (assuming it is actually the names of the servers and not their distinguished name)
Get-ADComputer -Filter * | Where { $_.DistinguishedName -like "*Computers*" -and $_.name -notin $excludedServers } | Select-Object Name

Getting AD users having a specific keyword within description field in AD

I want to get all of those users starting with a specific keywords in AD User Description field using PowerShell.
Keyword: Could not execute powershell
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase 'OU=contoso, DC=contoso, DC=local' - Properties Description | select -expand name,distinguishedname,description | Export-Csv -path C:\description.csv -NoTypeInformation
Last Update :
Get-ADUser -Properties Description -Filter 'Description -like "*Could not execute powershell*"' -SearchBase 'OU=contoso, DC=contoso, DC=local' |
select name,distinguishedname,description |
Export-Csv -path C:\description2.csv -NoTypeInformation
This is an easy task using the -filter option that you can use with get-aduser.
For more info how to filter: https://technet.microsoft.com/en-us/library/ee617241.aspx?f=255&MSPPError=-2147217396
Under the filter bit
Get-ADUser -Properties Description -Filter {Description -like $Description} -SearchBase 'OU=contoso, DC=contoso, DC=local' | select Name, DistinguishedName, Description | Export-Csv -path C:\description2.csv -NoTypeInformation
You can simply filter for Description:
Get-ADUser -Properties Description -Filter 'Description -like "*Could not execute powershell*"' -SearchBase 'OU=contoso, DC=contoso, DC=local'

Powershell group member ship field from AD

I have a powershell query here which look in a particular group in AD and extracts the users into a CSV. Currently it only extracts the SamAcountName and Display name. How would I get it extract the group membership of each user in that group ?
Get-ADGroupMember -identity GLS-IW-APP-QV-KPI-Full | select -Property Name,SamAccountName | Export-csv -path X:\QlikView_AD_Groups\GLS-IW-APP-QV-KPI-Full.csv -NoTypeInformation
So if you are looking to get the group membership of all users in a certain group this would be one approach. You need to add a calculated propery in your Select-Object
Get-ADGroupMember -identity GLS-IW-APP-QV-KPI-Full |
Select-Object -Property Name,SamAccountName,#{Label="MemberOf";Expression={(Get-ADUser -identity $_.SamAccountName -Properties memberof).memberof -Join ";"}} |
Export-csv -path X:\QlikView_AD_Groups\GLS-IW-APP-QV-KPI-Full.csv -NoTypeInformation
What the #{} portion does is take the SamAccountName and call Get-Aduser to extract the memberof property. Since that returns an object we concat that to a semicolon delimited string with a -Join for proper/better CSV output

Get Logged on Users from a List of Computer Names

I wanted to extract a list of users logged on to remote pc, the ps names would be fed in using a .csv file.
I was able to get a command
Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select Antecedent -Unique
to query the user names, could any one help me more on how to write this code?
Assuming the csv file contains a ComputerName header:
Import-Csv computers.csv | Foreach-Object{
Get-WmiObject Win32_LoggedOnUser -ComputerName $_.ComputerName | Select-Object __SERVER,Antecedent -Unique | Foreach-Object {
$domain,$user = [regex]::matches($_.Antecedent,'="([^"]+)"') | Foreach-Object {$_.Groups[1].Value}
$_ | Select-Object __SERVER,#{Name='Domain';Expression={$domain}},#{Name='User';Expression={$user}}
}
}

Resources