AD Users Script correction - windows

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.

Related

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

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

Copy Groups from one user to another in AD, except one specific group

Need help with adding a small comand to finish this pwoershell command.
I have this powershell command that copy groups from one user to another.
Now what i need is to add a command that will "Except" a specific group, like it will copy all the groups except one specific group.
Thanks for help.
Get-ADUser -Identity $Oldusername -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $Newusername
Get-ADUser -Identity $Oldusername -Properties memberof | Select-Object -ExpandProperty memberof | Where-Object { $_ -NotMatch $grouptoexclude } | Add-ADGroupMember -Members $Newusername
$grouptoexclude containing the name of the group you don't want the new user to be added into. It must be a distinguished name like CN=GroupName,OU=Groups,OU=Users & Workstations,DC=Fabrikam,DC=COM

How do I use the where-object cmdlet to find text that -contains a certain word

I'm setting up a contacts file in .csv format, as downloaded from google, to read with powershell on my windows 10 laptop. I have a long way to go to make this practical, but the first thing I've tried, and almost succeeded in, is to write a script that prompts the user to enter a name and then responds with the phone number for them. That script looks like this:
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="What's their name?")]
$TheirNameIs
)
Import-Csv "*MYPATH*.csv" |
Sort 'Family name' -descending |
Where-object {$_.Name -eq $TheirNameIs} |
Select-Object -Property 'Name','Phone 1 - Type','Phone 1 - Value'
The problem I am having is Where-object works with -eq to find exact matches to the name the user enters, but I wanted to use -contains so that I could type in a first name and get all the contacts with that value in their name. I tried replacing -eq with -contains but wasn't getting any output unless I used the exact contact name
Where am I going wrong with the Where-object cmdlet?
You could replace the -eq operator by the -like operator and insert wildcards:
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="What's their name?")]
$TheirNameIs
)
Import-Csv "*MYPATH*.csv" |
Sort 'Family name' -descending |
Where-object {$_.Name -like "*$TheirNameIs*"} |
Select-Object -Property 'Name','Phone 1 - Type','Phone 1 - Value'
You could also go for regular expressions and use the -match operator like #Olaf already mentioned. A solution could look like this:
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="What's their name?")]
$TheirNameIs
)
Import-Csv "*MYPATH*.csv" |
Sort 'Family name' -descending |
Where-object {$_.Name -match ".*$TheirNameIs.*"} |
Select-Object -Property 'Name','Phone 1 - Type','Phone 1 - Value'

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