Change output results in PowerShell - string

I want to get all user ID's with a specific token assigned.
It looks like this now when I run my script..
Get-ADUser -Filter * -Properties * | Select-Object vasco-LinkUserToDPToken, displayname
#Output#
vasco-LinkUserToDPToken Displayname
{CN=VES0423061,OU=br... User X
{} User X
{} User X
{CN=0067511310,OU=br... User X
{CN=0067077717,OU=br... User X
Example of a full vasco-LinkUserToDPToken :
{CN=VES0976944,OU=Internal Users,DC=mgm,DC=agf,DC=be}
the thing is I only want to filter VES + it should be shown like this (not containing empty strings or tokens that are not starting with VES):
VES0423061 User X

It looks like your property 'vasco-LinkUserToDPToken' is a multivalued property type (string array) of which you need to extract the DN inside.
You could try:
Get-ADUser -Filter "vasco-LinkUserToDPToken -like 'CN=VES*'" -Properties 'vasco-LinkUserToDPToken', DisplayName |
Select-Object #{Name = 'vasco-LinkUserToDPToken'; Expression = {
($_.'vasco-LinkUserToDPToken' | Where-Object {$_ -match '^CN=VES.*'}) -replace '.*(VES[^,]+).*', '$1'}
}, DisplayName
P.S. It is always a bad idea to use -Properties * is what you are after is just two properties. Using * forces to pull down ALL properties which is a waste of time
If the -Filter doesn't work on this custom property, you can always use a Where-Object clause afterwards like:
Get-ADUser -Filter * -Properties 'vasco-LinkUserToDPToken', DisplayName |
Where-Object { $_.'vasco-LinkUserToDPToken' -like 'CN=VES*' } |
Select-Object #{Name = 'vasco-LinkUserToDPToken'; Expression = {
($_.'vasco-LinkUserToDPToken' | Where-Object {$_ -match '^CN=VES.*'}) -replace '.*(VES[^,]+).*', '$1'}
}, DisplayName

Related

Partial Replace in Powershell

Let's say we have the following code
Get-ADUser -Filter {Enabled -eq $false} -properties * | sort Surname| FT GivenName, Surname, description
It produces:
GivenName Surname description
--------- --------- ------- -----------
Tom Abbott AccountingSystems
Tim Baker AccountingSystems
Tyler Cabot AccountingSystems
I need to put a space in between 'Accounting' and 'System'
I thought this would work:
Get-ADUser -Filter {Enabled -eq $false} -properties *
% {
$Description = $.replace("Accounting","Accounting ")
Set-ADUser = -Description $Description
}
But... it does not.
There are a few things I would recommend you look into,
There is no such variable as $. When you are looping through items with ForEach, you have to use $_ (with underscore)
You cannot assign value to a cmdlet (Set-ADUser = ).
You use | then % (not % | )
Try this,
Get-ADUser -Filter {Enabled -eq $false} -properties Description | % {
if ($_.Description) {
$description = $_.Description.replace("Accounting","Accounting ")
Set-ADUser $_ -Description $Description
} # else description is null.
}
Documentation for Set-ADGroup
Documentation for ForEach

Powershell odd behaviour when outputting to csv

I'm having a problem when outputting my foreach loop to a csv file.
My Groups are set like this:
$Groups = "Group1", "Group2", "Group3"
My code is:
$results = ForEach ($Group in $Groups) {
$memberof = get-adgroup $Group | select -expandproperty distinguishedname
Write-Output $Group
Get-ADObject -Filter 'memberof -eq $memberof -and (ObjectClass -eq "user" -or ObjectClass -eq "contact")' -properties * | select name, Objectclass, mail
Write-Output ""
Write-Output ""
}
$results | Export-csv Contacts.csv -NoTypeInformation
The problem seems to be coming from the Write-Output lines but I have no clue why. When I run my code without writing to a csv file, I get the expected result, something like:
NameOfGroup1
name Objectclass mail
---- ----------- ----
User1 user User1#mail.com
User2 user User2#mail.com
#Spaces caused by write-output ""
NameOfGroup2
User1 user User1#mail.com
Contact1 contact Contact1#externalmail.com
Then again when I run my code to write to csv file and have the write-output $Group commented out I get a similar result.
But if I run my full code from the top of this page including the write-output $Group, it comes out like this:
I've figured out what these results represent but I haven't got clue why they do print out like this.
Eseentially the numbers refer to the length of the group name, so the first 17 would be a 17 character group name, and then the number of lines below is equal to the number of contacts and users that are inside that group. The 2 zeros at the end of each group are the length of the write-output "" lines.
What is causing this behavior?
The following code will closely output what you are attempting.
$results = ForEach ($Group in $Groups) {
$memberof = get-adgroup $Group | select -expandproperty distinguishedname
Get-ADUser -Filter "memberof -eq '$memberof' -and (ObjectClass -eq 'user' -or ObjectClass -eq 'contact')" -properties name,ObjectClass,Mail | Select-Object #{n='Group';e={$Group}},name, Objectclass, mail
[pscustomobject]"" | Select-Object Group,Name,ObjectClass,Mail
[pscustomobject]"" | Select-Object Group,Name,ObjectClass,Mail
}
$results | Export-csv Contacts.csv -NoTypeInformation
Explanation:
Export-Csv converts an object or array of objects with properties into a CSV file. You can see the same result in the console with ConvertTo-Csv. Properties are converted into columns and property values are placed under their associated columns. When you output a string as in Write-Output $Group, it has a property of Length. To fix this, you need to add $Group as a calculated property in your Select-Object. If you want to do blank lines in your CSV, then you should output another object with all of the property values as ''.
When you mix objects in your PowerShell outputs, you can see unexpected results. Your Get-ADObject outputs a custom object. Your Write-Output lines output a string. Those two object types do not share properties. So you only see the properties for the first object in your array, which is a string. If you put all of the Write-Output statements at the end of your loop, you will see more properties in your CSV. See below for an example that just by reversing the order of processed objects, you get a different result.
$str = "string"
$obj = [pscustomobject]#{property1 = "value1"; property2 = "value2"}
$str,$obj | convertto-csv -notype
"Length"
"6"
$obj,$str | convertto-csv -notype
"property1","property2"
"value1","value2"
,
Notice the properties available to the custom object $obj and the string $str.
$obj | get-member -Type Properties
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
property1 NoteProperty string property1=value1
property2 NoteProperty string property2=value2
$str | get-member -Type Properties
TypeName: System.String
Name MemberType Definition
---- ---------- ----------
Length Property int Length {get;}

Pulling AD user data not working on telephone/employeeID PowerShell

This script isn't pulling ad user data like expected.This code is pulling the Name and UserPrincipalName correctly, but then it is blank for the rest of the fields.I know the fields that I am pulling are not blank. The result should be a csv file with the select-objects showing.Am I missing something? I am not getting an error message as well.
$OUpath = 'ou=*****,OU=****,DC=****,DC=****,DC=****,DC=****'
$ExportPath = 'c:\scripts\users_in_ou2.csv'
Get-ADUser -Filter * -SearchBase $OUpath |
Select-object Name,UserPrincipalName,mobile,mail,telephoneNumber,employeeID |
Export-Csv -NoType $ExportPath
You need to tell get-aduser which properties you want. There probably a better way too do it but this should get you the result you want
$OUpath = 'ou=*****,OU=****,DC=****,DC=****,DC=****,DC=****'
$ExportPath = 'c:\scripts\users_in_ou2.csv'
Get-ADUser -Filter * -SearchBase $OUpath -Properties Name,UserPrincipalName,Mobile,EmailAddress,telephoneNumber,employeeID |
Select-object Name,UserPrincipalName,Mobile,EmailAddress,telephoneNumber,employeeID |
Export-Csv -NoType $ExportPath

How can I split AD information in Powershell into a excel document?

I am a Powershell starter. I have been trying to create a script, that makes an Excel file with some AD information including the DistinguishedName. My script looks like this:
$dn = Get-ADUser -Filter * -SearchBase "OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads" | select DistinguishedName,SamAccountName,name |export-csv C:\temp\test1.csv -Delimiter ";"
An example of what I get (Note: | means new cell in Excel):
CN=Testuser\, Verfluecht,OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads | vtestuser | Testuser, Verfluecht
But in order to group the paths in excel, I need it without the CN (CN=Testuser\, Verfluecht,)
So that it would look like this:
OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads | vtestuser | Testuser, Verfluecht
How can I do this?
I tried many things such as .substring and replace, but I could not get it done.
Using this link and a calculated property, it should just drop the first part of the distinguishedname and be left with the parts you need.
Get-ADUser -Filter * -SearchBase "OU=Users,OU=Ch01,OU=EU,DC=corp,DC=ads" |
Select-Object #{Name="DistinguishedName";Expression={$_.distinguishedname | ForEach-Object {$_ -replace '^.+?(?<!\\),',''}}},samaccountname,name |
Export-Csv C:\temp\test1.csv -Delimiter ";"
On my test environment, I get the output below (without piping it to Export-Csv).
Get-ADUser -Filter * | Select-Object #{Name="DistinguishedName";Expression={$_.distinguishedname | ForEach-Object {$_ -replace '^.+?(?<!\\),',''}}},samaccountname,name
DistinguishedName samaccountname name
----------------- -------------- ----
CN=Users,DC=timhaintz,DC=com Administrator Administrator
CN=Users,DC=timhaintz,DC=com Guest Guest
CN=Users,DC=timhaintz,DC=com DefaultAccount DefaultAccount
CN=Users,DC=timhaintz,DC=com krbtgt krbtgt
Thanks, Tim.

How do I add another column to a System.Object using a list in Powershell?

I am making a script to query active directory via powershell and pull all computers that contain a username in the description field, then filter that list with only computers last logged in the past 14 days.
This is what I have so far:
$queryAD = Get-ADComputer -SearchBase 'OU=West Division,DC=cable,DC=comcast,DC=com' -Properties Name, Description -Filter {(Name -like "WA*") -and (Description -like $wildCard)} | Select-Object Name, Description
$lastLogon = $queryAD | Select-Object -ExpandProperty Description | %{$_.replace(("$NTname" + ";"),"").split(";")[0]} | %{get-date $_ -format d}
I'd like to add the list generated from $lastLogon to $queryAD, right now $queryAD is returning two columns with headers Name and Description. I need a third header added called Last Logon Date and contain the list in $lastLogon. Please advise.
You could assign the values to an array of objects to make your output cleaner (if this method is providing you the data you want) like so:
$queryAD = Get-ADComputer -SearchBase 'OU=West Division,DC=cable,DC=comcast,DC=com' -Properties Name, Description -Filter {(Name -like "WA*") -and (Description -like $wildCard)} | Select-Object Name, Description
$computer_list = #()
foreach($computer in $queryAD) {
$computer_info = New-Object PSObject -Property #{
Name = $computer.Name
Description = $computer.Description
LastLogonDate = $computer | Select-Object -ExpandProperty Description | %{$_.replace(("$NTname" + ";"),"").split(";")[0]} | %{get-date $_ -format d}
}
$computer_list += $computer_info
}
in which case $computer_list will contain all of the info you're gathering in tidy objects.
...but this method seems overcomplicated. Look into this blog entry by Matt Vogt for a better way to query for old machines in AD.

Resources