AD User Array CSV search and analyze error - arrays

i want to search to an exported Active Directory list but i got one problem.
AD Files looks like this and its saved as CSV-File (I added a Header to the file)
CN=ARV-PRO7,OU=etc,OU=etc,DC=etc,DC=etc,DC=etc
CN=BLAPO86z,OU=etc,OU=etc,DC=etc,DC=etc,DC=etc
This is a example (there are 37 more entrys like ARV in the "where" is shoreted it for better view) of the Code im trying to run:
$Datei = Import-Csv "C:\FILESPATH\AD-list.csv"
$Datei | where {$_.CN -notmatch "ARV" -and $_.CN -notmatch "BBN"} | Out-GridView -Title "Site Info"
This shows me all the items with no ARV in it, thats what i want.
BUT it ignores also the items which looks like this:
CN=PR122ARVO7,OU=etc,OU=etc,DC=etc,DC=etc,DC=etc
Because ARV is in the name the item is not shown.
I need a way to check if the first 3 letter ARV than its okay and he can ignore it but i also need him to show me names with ARV in it to check the name rules. ( Department-PCNAME ) and not (BLABLA-PC-DEPARTMENT-NAME)
I Hope its clear what iam asking and what my problem is ^^

If I understand correctly, you would like to ignore items starting with ARV. This should work (simplified, only where section is important here):
#{CN='ARV-PRO7'},
#{CN='BLAPO86z'},
#{CN='PR122ARVO7'} | where { !$_.CN.StartsWith('ARV') }

Related

Powershell - Exporting data from powershell into a csv file using custom objects

So I received a list of users from a co-worker who needed to confirm who in the list was still employed and who wasn't. I chose to filter out all users that either didn't exist in AD or were disabled and assign them to $TerminatedUser. I took all active users that assigned them to $EmployeedUser. (I know I spelled "Employed" wrong) I then tried to use the data from $EmployeedUser and $TerminatedUser and create a report within $EmployementStatus.
What I end up with is two columns which is awesome but I also only get 1 cell for each column. All the data for each column is bunched into one cell which makes it hard to read. At first when outputting $EmployementStatus to a csv file was only getting the headers and [system.object] for each cell. I was able to get around that.
So my question here now is: Is it possible to export $EmployementStatus to a csv where the data is listed out and each "Employed"/"Terminated" user receives their own cell as opposed to them all being bunched in cells A2 and B2?
Teach me something!
This is sample code, since I'm not going to type out all that stuff again. And it isn't tested.
What you want, apparently, is to check there's an enabled AD user account that matches your userlist. For Powershell versions greater than 3.0, you can output [pscustomobject] directly into an array from a Foreach.
You just need ONE query to AD to determine if a user exists and whether the account is enabled ("Enabled" is one of the default properties returned in Get-AdUser).
It's probably more convenient for output if you simply have a "Verified" column and set that to TRUE or FALSE. Or you can have a "Status" column and output text to that like "Disabled" or "NotPresent" or "Verified". Whatever, really, I'm going with the easiest.
The try/catch is so you don't get a load of errors when the user doesn't exist. If you want to set different statuses for each "state", then you can place strings in there rather than $true/$false.
$employmentStatus = Foreach ($GID in $MyList) {
$ID = $GID.SamAccountname
try {
# if the user isn't found, it'll go to the Catch block after the next line
$u = get-aduser $ID -erroraction stop
if ($u.enabled) {
$verified = $true
}
else {
$verified = $false
}
}
catch {
# if the user doesn't exist, they're not verified
$verified = $false
}
# output the per-user status as a pscustomobject in $employmentStatus
[pscustomobject]#{
ADUser = $ID
Verified = $verified
}
}
You should find that if you process your userlist with that, you can check the result with $employmentStatus | out-gridview.
That should show the "AdUser" and "Verified" columns, with TRUE or FALSE for each user.
If that looks OK, so will your CSV export: $employmentStatus | export-csv [path].
If you're using an old PS version, then you may need to predefine your output array as you did originally. Then you'd just fix up the line with the [pscustomobject] to append it to the array. Everything else works the same.
$employmentStatus = #()
Foreach ($GID in $MyList) {
...
# output the per-user status as a pscustomobject - append to $employmentStatus
$employmentStatus += [pscustomobject]#{
ADUser = $ID
Verified = $verified
}
}

Powershell: Comparing a value between two arrays, and extracting a related value

so here is what I'm trying to accomplish.
I have a form for a new starter, New Starter Form.csv, that has the following headers and information:
firstname,lastname,teamname,startdate
Joe,Bloggs,Security Admin,01/01/18
I have a different csv called Team List.csv, that has the following headers and information:
teamlead,teamname,resgroup
A B,Marketing,RESMARKETING01G
C D,Product,RESPRODUCT01G
E F,Advertising,RESADVERTISING01G
G H,Security Admin,RESSECURITYADMIN01G
I want to import both CSV files into Powershell, run a comparisson that takes the team name from the New Starter Form, and checks if there are any matches in the Team List, and if so, add the relevant RES group to the new starter in AD.
Currently, I can import them, compare them, find a match, and find an index number for the record, but I'm struggling to the take this index number, and use it to get the relevant RES group. So far the code looks like this:
$teamlist = import-csv "\\location\Team List.csv"
$newstarter = import-csv "\\otherlocation\New Starter Form.csv"
[string]$teamname = Compare-Object -includeequal -excludedifferent -PassThru $newstarter.teamname $teamlist.teamname
$teamname
[array]::indexof($teamlist,$teamname)
And running that, provides us with this in the console, showing that we can indeed see the match, and that the matching record is the last (-1) one:
PS C:\WINDOWS\system32> $teamlist = import-csv "\\location\Team List.csv"
$newstarter = import-csv "\\otherlocation\New Starter Form.csv"
[string]$teamname = Compare-Object -includeequal -excludedifferent -PassThru $newstarter.teamname $teamlist.teamname
$teamname
[array]::indexof($teamlist,$teamname)
Security Administration
-1
I've not got a lot of experience with Powershell, and my coding knowledge is pretty limited overall, but I'm used to the concept that I can save the index value as a variable, and then I could call that variable back to do something like $teamlist.resgroup[VARIABLE HERE].
But if I try and declare a new variable before [array]::indexof($teamlist,$teamname), Powershell isn't happy.
Whilst I've not looked into it, I believe a possible alternative could be to add in a huge switch statement, but I may be looking at having 100+ teams overall, and I'd like to avoid inefficient code wherever I can. Am I missing something obvious though? Is there a better way (Or even just a functioning way would be great!) that this could work?
Any help you can provide would be greatly appreciated!
$teamlist = import-csv "\\location\Team List.csv"
$newstarter = import-csv "\\otherlocation\New Starter Form.csv"
# get a single new starter
$person = $newstarter | Where-Object { $_.firstname -eq 'Joe' -and $_.lastname -eq 'Bloggs' }
# get the new starters team
$team = $teamlist | Where-Object { $_.teamname -eq $person.teamname }
# get the new starters resource group
$resgroup = $team.resgroup
# use the resource group - this simply writes it to the console
Write-Host $resgroup
The code above will:
import your two csvs
grab a single new starter from your new starter csv, based on first &
last name
grab the team & resource group for that new starter from the team list
display the resgroup (this is where you will need to use to populate AD)

filling attribute with concatenated string

I am looking for a way to concatenate a string and put it in one active directory user account object, to be precise, in altsecurityidentities.
The value to be input will be as following:
" which is constant, and (firstName)(whitespace)(lastname) (custom value which can be taken from another attribute, which is in form x.yyyyyyyy.z (what matters to me is yyyyyyy part (.substring(2,8)) works like charm here.
I'd like to do it for several accounts that are listed in variable of type TypeName: Microsoft.ActiveDirectory.Management.ADUser.
So that it can be set for all accounts under $accounts variable.
So far I have the code to create the attribute value for one account listed in there:
$accounts | %{'constant value'+$.givenname+' '+$.surname+' '+'('+$(($_.attributename).substring(2,8))+')'}
This, i'd like to put in altsecurityidentities attribute value, log to event viewer success and errors
You're almost there really just need to apply the value to the desired field:
$accounts | ForEach-Object { Set-ADUser -Identity $_ -Add #{altsecurityidentities = "constant value $($_.givenname) $($_.surname) ($($_.attributename.substring(2,8)))"} }
I have tidied up your code by embedding the variables in a string rather than using concatenation, which is much cleaner.

How do I save CSV data to variables based on a ListBox selection?

I have a drop down list in my script that gets populated by the "name" column in a CSV file. I'd like to save the information in the other columns that go with that name into variables to be used later.
For example (bullets are there so they show underneath each other, showed as one line otherwise):
Name,Address,PhoneNumber,Email
Bob,1234 Bob Rd,123-4567,bob#email.com
Bill,5678 Bill Ave,246-8024,bill#email.com
The drop down list would show Bob and Bill. Based on what I pick I'd like the rest of their info to be saved into 3 different variables, $Address, $PhoneNumber, and $Email.
I've got as far as importing the CSV into the array and sorting them alphabetically.
$Customers = #(Import-CSV "$dir\Apps\Customers.csv")
$Array = $Customers.name | Sort-Object
Here's part of the drop down box code:
ForEach ($Choice in $Array) {
[void] $companybox.Items.Add($Choice)
}
After that I can't figure out how to grab the correct information based on what's been chosen when I click a button.
Here's the button code:
$handler_gobutton_Click = { $company = $companybox.SelectedItem
....
}
I have a few If statements in there right now for an earlier solution that doesn't use CSV's, but I'd like to move to a CSV file if possible.
Thanks!
EDIT: I'm thinking what I need to do is somehow find the array count number based on the name column. After that I should be able to save $array[0].address into a variable, for example. Finding how to compare the variable with the name in it to the name in the array and from that getting the count number is coming up empty so far... Ideas?
Got it to work!
$handler_gobutton_Click = {
$company = $companybox.SelectedItem
$index = [array]::IndexOf($customers.name,$company)
If ($customers[$index].uninstall -eq "True") { $uninstallbox.checked = $True }
... and so on
}
Source: https://www.reddit.com/r/PowerShell/comments/t1928/finding_array_index_number/

Powershell - compare Active Directory usernames with e-mail address

I am currently trying to find all AD users that have been created using the model "firstname#domain.com" versus our new standard of "FirstInitialLastName#domain.com". I'm using the Quest ActiveRoles modules, specifically Get-QADUser to pull down my user details:
Get-QADUser -enabled -IncludedProperties PrimarySMTPAddress | ?{$_.Type -match "User"} | Select-Object FirstName,PrimarySMTPAddress ...
That gets me a list of user first names and their SMTP address. Where I am stumped is how to compare the results.
I thought normalizing the values (either adding "#domain.com" to the first name string or stripping "#domain.com" from the SMTP string) and then doing a -ieq test would be the best approach. I have found I can do the first with:
%{ $address=$($_.FirstName + "#domain.com";) }
But I can't figure out how to then test $address against the PrimarySMTPAddress string. I can create a second variable with:
%{ $smtp=$($_.PrimarySMTPAddress); }
and get the result:
[PS] C:\>$addy -ieq $smtp
True
I'm just unclear how to do it all in stream so that I can process my tree at once. If this is something that's just more suited to a script than a single line, that's fine too. Coming from the glorious world of BASH my brain just wanted to one-line it.
Get-QADUser -Enabled -Email * -SizeLimit 0 |
Where-Object {$_.Email.Split('#')[0] -eq $_.FirstName }
Try this:
Get-QADUser -enable -IncludedProperties PrimarySMTPAddress |
? { $_.PrimarySMTPAddress -match ("^"+[regex]::escape("$($_.firstname)")+"#domain.com") }

Resources