Using a .txt file to populate a Powershell Script - powershell

I have a Powershell script that queries Active Directory, by User ID, and outputs to a .csv file listing user attributes that I specify.
The script works flawlessly for a single user, but I would like to use a text file, with a list of users, to populate the script and create output for multiple users all at once.
Please advise.
This is my original script pulling the user list from a specific OU:
import-module ActiveDirectory
$ADGroupParams=#{
'Server' = 'corp.xxxx.com'
'Searchbase' = 'OU=Security Groups,DC=corp,DC=xxxx,DC=com'
'Searchscope'= 'Subtree'
'Filter' = '*'
'Properties' = '*'
}
$SelectParams=#{
'Property' = 'cn', 'managedBy', 'info', 'sAMAccountName', 'created'
}
get-aduser #ADGroupParams | select-object #SelectParams | export-csv "C:\Scripts\Users_By_OU.csv"

Assuming your text file is a txt file with one username per line:
# Put all ADUser properties you want dumped to the CSV in an array
$adUserProperties = #(
'one',
'attribute',
'per',
'index'
)
# Read the users from the file, get the ADUser object for each one,
# selecting the properties you want dumped to the CSV, and export the
# returned information to a CSV file.
Get-Content \path\to\users.txt | Foreach-Object {
Get-ADUser -Filter "SamAccountName -eq '$($_)'" -Properties $adUserProperties
} | Select-Object -Properties $adUserProperties | Export-Csv -NoTypeInformation users.csv

Related

I want to import CSV file, a list of group members to Distribution group name is ibv europa, but following script not working

$users = import-csv "c:\temp\merged11.csv" | ForEach-Object {Add-DistributionGroupMember -Identity "IBV Europa" }
we have removed "" from CSV file and it's now include only column of all email addresses.
I have tried different syntax's but won't helpful.
If you just have one column with the mail addresses, i would use get-content instead of import-csv and remove the header from the csv file.
merged11.csv Example:
User1#test.com
User2#test.com
User3#test.com
and the Powershell Script could be like this:
$UserEMailList = get-content "c:\temp\merged11.csv"
$UserEMailList | ForEach-Object {
Add-DistributionGroupMember -Identity "IBV Europa" -Member $_
}

removing 'CN' from DistinguishedName in Powershell script

I have the below script that I use to periodically export the list of users in all of the OUs in AD, and it works pretty well, but 'DistinguishedName' isn't all that great to have as an output as it makes it hard to filter the output by OU. I've been looking, and it should be possible to remove the 'CN=' portion, leaving just the OUs, but scripting is my Achilles Heel and everything I've tried to add in from examples I've found has either returned strange results or blown up when run. How could the below script be modified to make the last column the Distinguished Name minus the 'CN=_______,'?
import-module ActiveDirectory
#Set the domain to search at the Server parameter. Run powershell as a user with privilieges in that domain to pass different credentials to the command.
#Searchbase is the OU you want to search. By default the command will also search all subOU's. To change this behaviour, change the searchscope parameter. Possible values: Base, onelevel, subtree
#Ignore the filter and properties parameters
$ADUserParams=#{
'Server' = 'DC01'
'Searchbase' = 'OU=Users,OU="OU2",OU=OU1,DC=Domain,DC=Local'
'Searchscope'= 'Subtree'
'Filter' = '*'
'Properties' = '*'
}
$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
#This is where to change if different properties are required.
$DNList | ForEach-Object{($_ -split "," | Select-Object -Skip 1) -join ","}
$SelectParams=#{
'Property' = 'DisplayName', 'SAMAccountname', 'enabled', 'lastlogondate', 'logoncount', 'passwordlastset', 'created', 'DistinguishedName'
}
get-aduser #ADUserParams | select-object #SelectParams | #DNList | export-csv "c:\temp\userlist_test_$(get-date -f yyyy-MM-dd).csv"
First things first, 'Properties' = '*' is not a good idea, you would be querying for all user's Attributes when you only need those in $ADUserParams. You should always query for those attributes you actually need as, not only, your query will run faster but also it will have less impact on your Domain Controller(s) depending on the size of it and how many objects you have in your Domain.
As for getting the Organizational Unit from the user's DistinguishedName, I personally would use any of the nice regexes shown in this question, for this particular example I'm using the one shown in mjolinor's answer which would suffice in almost any case.
The code would look like this:
$ADUserParams = #{
Server = 'DC01'
Searchbase = 'OU=Users,OU="OU2",OU=OU1,DC=Domain,DC=Local'
Searchscope = 'Subtree'
Filter = '*'
Properties = #(
'DisplayName'
'SAMAccountname'
'enabled'
'lastlogondate'
'logoncount'
'passwordlastset'
'created'
'DistinguishedName'
)
}
Get-ADUser #ADUserParams | Select-Object #($ADUserParams.Properties + #{
Name = 'OU'
Expression = { $_.DistinguishedName -replace '^CN=.+?(?<!\\),' }
}) | Export-Csv path\to\export.csv -NoTypeInformation
you can accomplish that retrieving also name attribute, then you can create a calculated property
#{l='OU';e={$_.distinguishedname -replace "CN=$($_.name),"}}
where you replace name data with in distinguishedname string.
$SelectParams=#{ 'Property' = 'DisplayName', 'SAMAccountname', 'enabled', 'lastlogondate', 'logoncount', 'passwordlastset', 'created', 'DistinguishedName','name' ,#{l='OU';e={$_.distinguishedname -replace "CN=$($_.name),"}}}
get-aduser #ADUserParams | select-object #SelectParams

Trying to find a way to speed up this powershell script

I have this script that works fine (output looks good), but it is taking longer than 12 hours now. There are 34220 records in the csv and it's only now on 2110. Maybe I need to load up all the user data first, then compare to the csv file? Thx for help...
import-module ActiveDirectory
$CCure = Import-csv C:\Scripts\CCure\CCure-Personnel-enabled.csv
ForEach ($Row in $CCure) {
[string]$ID = $Row.ObjectID
[string]$Name = $Row.Name
[string]$EmpID = $Row.Int5
If ($EmpID.Trim() -ne "0") {
$User = Get-ADUser -LDAPFilter "(&(&(&(objectclass=user)(objectcategory=person)(!userAccountControl:1.2.840.113556.1.4.803:=2))))((employeeId=*$EmpID))" -SearchBase 'DC=Enterprise,DC=mycompany,DC=org' -Properties SamAccountName,DisplayName,EmployeeId,enabled |
Select #{Name="CCure ObjectID";Expression={$ID}},SamAccountName,DisplayName,#{Name="CCure Name";Expression={$Name}},EmployeeId,#{Name="CCure Int5 Row";Expression={$EmpID}},enabled | Export-csv c:\scripts\ccure\EmployeeIds4-10-2016.csv -NoTypeInformation -append
}
}
Maybe I need to load up all the user data first, then compare to the csv file?
That's exactly what you need to do!
Since you want to correlate the users in the CSV by the EmployeeId attribute, I'd recommend pulling out all the (enabled) users that have the EmployeeId populated, and then store them in a hashtable where the EmployeeId is used as the key:
$ADUserTable = #{}
Get-ADUser -LDAPFilter "(&(!userAccountControl:1.2.840.113556.1.4.803:=2)(employeeId=*))' -SearchBase 'DC=Enterprise,DC=mycompany,DC=org' -Properties SamAccountName,DisplayName,EmployeeId |ForEach-Object {
$ADUserTable[$_.EmployeeId] = $_
}
Then, as you iterate over the rows in the CSV, lookup the user in the hashtable instead of searching AD again:
$ExistingUsers = ForEach ($Row in $CCure) {
# Import-Csv always creates string properties anyways
$ID = $Row.ObjectID
$Name = $Row.Name
$EmpID = $Row.Int5.Trim()
if ($EmpID -ne "0" -and $ADUserTable.ContainsKeys($EmpID))
{
$ADUserTable[$EmpID] |Select #{Name="CCure ObjectID";Expression={$ID}},SamAccountName,DisplayName,#{Name="CCure Name";Expression={$Name}},EmployeeId,#{Name="CCure Int5 Row";Expression={$EmpID}}
}
}
Do NOT export them to Csv until AFTER you've collected all the information - otherwise you're opening, writing to and closing the same file 35000 times!
So, at the very end:
$ExistingUsers |Export-csv c:\scripts\ccure\EmployeeIds4-10-2016.csv -NoTypeInformation
This will undoubtedly speed up execution of your script
Note: I've removed the Enabled property from Get-ADUser and Select-Object. Your LDAP Filter already guarantees that only Enabled users are returned, so I don't really see any value in adding it to the CSV

Get sAMAccountNames from CSV of Employee IDs powershell

Im not sure why I cannot get this to work, but I have a .csv of employee ID's and I want to add them to an AD group, but I cannot get this to work
Function Sync-ADGroup {
$userIDs = Import-CSV $CSV
foreach($ID in $IDs){
Get-ADUser -Filter "EmployeeID -eq '$ID'" -Properties SAMAccountName
}
}
Then I would add them to the group, but I cannot it to return the ADUserObject. Not sure what I am missing.
You need to reference the property name (column) of the user as it appears in the csv file. For example, if the value in the file is under the EmployeeID header:
foreach($userID in $userIDs)
{
Get-ADUser -Filter "EmployeeID -eq $($userID.EmployeeID)" -Properties SAMAccountName
}
For the above to work your csv file needs to look like:
EmployeeID
1234
2345
3456
Undeclared collection variable is used in foreach loop.
$userIDs = Import-CSV $CSV # Load stuff to "userIDs"
foreach($ID in $IDs){ # Enumerate "IDs", oops, should be "userIDs"
As $IDs is empty a variable, the loop doesn't do much.
In order to avoid this kind of errors, use the strict mode: Set-PSDebug -Strict. This will rise an error for using undeclared variable. (Rant: the strict mode should be the default in Powershell. I set it in my profile and all the scripts I write for good measure.)

Powershell - Adding users to AD group from a CSV file

I know this has been done to death but im useing this as a learning experience with powershell. Could someone take a look at my code and tell me where i am going wrong? Noob code warning!
#
# Add User to an AD Group
#
#
# get arguements and quit if they dont exist
$CSV = $args[0]
$GROUP = $args[1]
if (! $CSV) {
Write-Host "Please format this command as 'AddUsersToGroup <csv file> <AD group>'"
Write-Host "CSV file must have the header 'UserName' with AD usernames following"
exit
}
# Read csv file for users and add to AD group
Import-module ActiveDirectory
Import-CSV "$CSV" | % {
# Get existing users from AD group
$ExistingGroup = "Get-ADGroupMember $GROUP | Select-Object SamAccountName"
# create new array removing existing users from the csv
$NewGroup = $ExistingGroup | where {$CSV -notcontains $_}
# add the users to the AD Group from the new array
Add-ADGroupMember -Identity $NewGroup -Member $_.UserName
exit
}
try delete double quote here:
$ExistingGroup = Get-ADGroupMember $GROUP | Select-Object SamAccountName
with quote you're assign a string value to variable not the results of your commands