Powershell - trimming/splitting an object to export-csv - powershell

I am trying to do a very simple task in powershell, I am trying to export a list of users from AD with certain properties. The problem is I need to trim the manager property to only include the name not the OUs etc. When I do this though I have to convert the object to a string which then I cant export to csv and cant get convertto-csv to work.
Get-ADUser gmclean -Properties * | Select sapid,EmailAddress,GivenName,Surname,department,costcenter,Title,Office,MobilePhone,StreetAddress,City,State,PostalCode,Country,manager
sapid : 111111
EmailAddress : test#123.ca
GivenName : Gray
Surname : Mclean
department : Edmonton Sales
costcenter : 213456
Title : Account manager
Office : EDM
MobilePhone : 123456789
StreetAddress : 123 street sw
City : Edmonton
State : AB
PostalCode : Z2Z Z2Z
Country : CA
manager : CN=Tea Ping,OU=Users,OU=EDM,OU=CA,OU=Countries,DC=test,DC=testinc,DC=ca
In this I am able trim the manager property and combine the variables. But I cant figure out how to make headers for all the properties.
$Everything = Get-ADUser gmclean -Properties * | Select sapid,EmailAddress,GivenName,Surname,department,costcenter,Title,Office,MobilePhone,StreetAddress,City,State,PostalCode,Country | ForEach-Object {$_.sapid,$_.EmailAddress,$_.GivenName,$_.Surname,$_.department,$_.costcenter,$_.Title,$_.Office,$_.MobilePhone,$_.StreetAddress,$_.City,$_.State,$_.PostalCode,$_.Country} | Out-string
$manager = Get-ADUser gmclean -Properties * | Select -Property manager | Out-string
$manager1 = $manager.split("="",")
$manager2 = $manager1[1]
$Everything1 = $Everything+$manager2
$Everything1
111111
test#123.ca
Gray
Mclean
Edmonton Sales
213456
Account manager
EDM
123456789
123 street sw
Edmonton
AB
Z2Z Z2Z
CA
Tea Ping
I am sure there is an easier way to do this but unfortunately I cant seem to figure it out.
Thanks,

Use a calculated property on your first pass through Select (all the way at the end):
Get-ADUser gmclean -Properties * | Select sapid,EmailAddress,GivenName,Surname,department,costcenter,Title,Office,MobilePhone,StreetAddress,City,State,PostalCode,Country,#{Name='manager';Expression={$_.manager.Split("=,")[2]}}

Related

How to export a multi line CSV that every item is in one cell?

I'm kinda new into the PowerShell world related to building gui's but I've managed to create a gui that in a few words, searches users in an AD and if the looked up information is correct it will store it on a CSV with the Out-File command.
An example looks like this.
Enabled : False
Locked : False
DisplayName : John Doe_test
GivenName : John
SurName : doe_test
SamAccountName : johndoe
Mail : ftestaddress#somemail.com
OfficePhone : 9999
Last Logon : 31/12/1600 21:00:00
Date Created : 7/6/2020 18:02:56
passwordlastset : 7/6/2020 18:02:56
And the code that outputs that is this one (this is the part that searches the user, displays it on a read only textbox and if the end user is right with the click of another button it will store the data. (The Write Host value is only to test the data, otherwise I'll have to enter to the csv file every time I store it.
$Formselected.controls.addrange(#($datousr,$save_btn))
$datousr.Text= Get-ADUser -filter {DisplayName -eq $username} -Properties * |Select-Object Enabled, #{Expression={$_.LockedOut};Label='Locked';}, DisplayName, GivenName, SurName, SamAccountName, Mail, OfficePhone, #{ Expression ={[DateTime]::FromFileTime($_.LastLogon)}; Label='Last Logon';}, #{Expression={$_.Created};Label='Date Created';}, passwordlastset | Out-String
$data_usr=$datousr.text
$save_btn.Add_Click{
Write-Host "$data_usr"
$data_usr |Out-File "C:\scripts\data load.csv" -Encoding UTF8 -Append -Force
}
I want to know, because it's driving me nuts how to assing "enable" on A1 and the result, which is "False" on A2 and so on because every item is in a line.
I've tried exporting to csv, but, because it comes from a variable it only stores the length of the output, not the value.
I'd like to be stored in this way:
Enabled Locked Username
False False JohnDoe
Export-CSV has a switch called -NoTypeInformation. With that appended to the cmdlet it saves the data only. However, you need to keep the data as Object for this, not converted to string as you have it now.
To do this, change the code block where the user information is gathered from AD into this:
# properties DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName are returned by default.
$props = 'LockedOut','DisplayName','EmailAddress','OfficePhone','LastLogonDate','Created','PasswordLastSet'
# use the `script:` scope on the variable, so the button click has access to it
$script:data_usr = Get-ADUser -Filter "DisplayName -eq '$username'" -Properties $props -ErrorAction SilentlyContinue |
Select-Object Enabled,
#{Name = 'Locked'; Expression = {$_.LockedOut}},
DisplayName, GivenName, SurName, SamAccountName,
#{Name = 'Mail'; Expression = {$_.EmailAddress}},
OfficePhone,
#{Name = 'Last Logon'; Expression = {$_.LastLogonDate}},
#{Name = 'Date Created'; Expression = {$_.Created}},
PasswordLastSet
# display the data in the text box by formatting it as list and converting it to a string
$datousr.Text = ($data_usr | Format-List | Out-String)
Then in the code where you save the data to CSV, do:
$save_btn.Add_Click({
Write-Host $data_usr # display in the console
# save as proper CSV file (append to if the file already exists)
$script:data_usr | Export-Csv -Path "C:\scripts\data_load.csv" -Encoding UTF8 -Append -NoTypeInformation
})
Please note that it is better to name the properties you need from Get-ADUser then to use -Properties *. You don't need to add the properties returned by default (see the first code comment)
Also, I would recommend searching for the user on a user attribute other then the users DisplayName, because this tends the users of your GUI to enter variations like Bloggs, Joe vs. Joe Bloggs. EmailAddress could be more precise.

Removing samaccountname from group after N time - powershell

I am looking to find a way to remove a user from a group after a specific amount of time.
Via the below link I found that you can find users that were added with 10 days or more:
https://gallery.technet.microsoft.com/scriptcenter/Find-the-time-a-user-was-a0bfc0cf#content
As an output I get the example below:
ModifiedCount : 2
DomainController : DC3
LastModified : 5/4/2013 6:48:06 PM
Username : joesmith
State : ABSENT
Group : CN=Domain Admins,CN=Users,DC=Domain,DC=Com
I would like to return SamAccountName instead of Username.
I was trying to look at code and I know this is something to do with the variable $pattern But I am not that good in powershell to know at first sight.
Looking at that code, the Username property IS the SamAccountName.
However, if you want to change that label, you can either simply change it on line 106 from
Username = [regex]::Matches($rep.context.postcontext,"CN=(?<Username>.*?),.*") | ForEach {$_.Groups['Username'].Value}
into:
SamAccountName = [regex]::Matches($rep.context.postcontext,"CN=(?<Username>.*?),.*") | ForEach {$_.Groups['Username'].Value}
Or change the label in the objects returned afterwards with a calculated property:
$returnedObjects | Select-Object #{Name = 'SamAccountName'; Expression = {$_.Username}}, * -ExcludeProperty Username

PowerShell Output Related to ADObject Properties

I'm trying to retain the Microsoft.ActiveDirectory.Management.ADAccount object when searching and specifying return outputs; however, when selecting the outputs, additional fields are populating. Questions:
Why is this is happening?
Is there a method, command, or filter to return only the specified parameters? (not the extra fields listed in the example below)
Is there a way to remove properties from the ADAccount Object? ($a in this example)
For the select method, is there a way to retain the original object formatting ? (I do not want a table and still need to reference the object later)
Running the following command:
$a = Get-ADUser $targetPerson -Properties Department, EmailAddress, Office, OfficePhone
returns:
Department : ****
DistinguishedName : CN=1111,OU=2222,OU=3333,OU=4444,DC=5555,DC=6666
EmailAddress : ****#mail.com
Enabled : ****
GivenName : ****
Name : ****
ObjectClass : user
ObjectGUID : ****
Office : ****
OfficePhone : ****
SamAccountName : ****
SID : ****
Surname : ****
UserPrincipalName : ****
Get-ADUser has a default set of properties it always returns, including for instance the distinguished name, the SID, and the account name. The parameter -Properties is for specifying which additional properties the cmdlet should return, because the default property set is just a small subset of all available properties.
To limit the output of Get-ADUser to a specific set of properties you need to pipe the output through Select-Object:
$props = 'Department', 'EmailAddress', 'Office', 'OfficePhone'
$a = Get-ADUser $targetPerson -Properties $props |
Select-Object $props
Of course that will turn the ADAccount object into a custom object (PSCustomObject), but I don't think there's a way around that.
The object Microsoft.ActiveDirectory.Management.ADAccount inherits members from the class it is created from. Here are some of the inherited members -
Name, ObjectClass, ObjectGUID, SID, and SamAccountName.
More about AD Object
I don't think you can create a Microsoft.ActiveDirectory.Management.ADAccount object with out those inherited members.
But if your project can accept a PSCustomObject then pipe $a to Select-object.
$a | Select-Object -Property Department, EmailAddress, Office, OfficePhone

How to get object type/identifier?

In PowerShell, when I work with Active Directory specifically, often I'll compile an object containing a list of groups of people usually with $x = get-adgroup -filter {name -like "*"} | select-object name which gives me a list with a header or object type name:
name
----------
name1
name2
name3
How can I access the name header of the object or even change it to something else?
Can it be done similarly to the way I would access the string of the first entry like $x[0].name?
Further, is there a more generic way to access the string associated with an arbitrary entry?
I'm being asked to a lot of "programming" in PowerShell related to AD so any resources you can provide to help me would be greatly appreciated.
If you want to change the name you can create an expression for it in your select block:
get-adgroup -filter {name -like "*"} | select-object #{Name="WhatYouWannaCallIt";Expression={$_.Name}}
This would now give you:
WhatYouWannaCallIt
------------------
name1
name2
name3
The two things that I think you are asking for is a programmatic way to determine the name of a given property in an object.
(get-aduser $user | select name).psobject.properties
MemberType : NoteProperty
IsSettable : True
IsGettable : True
Value : Matt
TypeNameOfValue : System.String
Name : name
IsInstance : True
The Name property of .psobject.properties contains most of this information and I think you might be looking for.
Was going to answer the second part with what Arco444 just said about using select-object
Do you mean:
$x = get-adgroup -filter {name -like "*"}
$x.name
or
(get-adgroup -filter {name -like "*"}).name

Power Shell Output Re-Filter | Get-CalendarProcessing

I'm trying to write a script that shows resource delegates in Outlook 2010 mailboxes. The code for this is:
input > Get-CalendarProcessing -Identity $Alias | where {$_.ResourceDelegates -ne "{}"} | ft *
The output important to me is the Resource and Mailbox identity.
ResourceDelegates : {TEST/A/A Usr, TEST/A/Kelly Besant, TEST/A/A Usr,
Identity : TEST/A/A Usr
I need the names in a standard format and not in the canonical format, how can I convert them?
You can use the canonical name with get-recipeint to resolve to Name, DisplayName, or DN:
Get-CalendarProcessing -Identity $Alias |
where {$_.ResourceDelegates -ne "{}"} |
select -ExpandProperty ResourceDelegates |
get-recipient |
select -ExpandProperty Name
Each ResourceDelegates or Identity object has a name property (EMS required):
$Identity = #{n='Identity';e={$_.Identity.Name}}
$ResourceDelegates = #{n='ResourceDelegates';e={$_.ResourceDelegates | foreach {$_.Name}}}
Get-CalendarProcessing $alias| Select-Object $Identity,$ResourceDelegates