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

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.

Related

Change output results in PowerShell

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

Get-AzureADAuditDirectoryLogs format issue

I have this below script
Get-AzureADAuditDirectoryLogs | more
It will provide the output as below as expected;
enter image description here
But when we try to export this to a .csv I am not getting the output properly
Get-AzureADAuditDirectoryLogs | more | Export-Csv C:\temp\securitylogs.csv -NoType
If you see TargetResources or Additionaldetails columns its capturing something else which is not in the actual output. Can someone please tell us what we are missing here in Export-csv command?
enter image description here
Those properties cannot be accessed directly. I have given a reference code to display those properties.
$users = #()
$logs = Get-AzureADAuditDirectoryLogs
foreach ($log in $logs) {
$obj = [PSCustomObject]#{
ActivityDateTime = $log.ActivityDateTime
UserPrincipalName = $log.TargetResources.UserPrincipalName
Category = $log.Category
}
$users += $obj
}
$users | Export-Csv C:\Output\SomeFilename.csv -Force -NoTypeInformation
And also, you have to filter the logs using unique properties or matching some condition(like date), otherwise your output file will have multiple varieties of data.
sample:
Get-AzureADAuditDirectoryLogs -All $true -Filter "activityDateTime le 2021-11-29 and Category eq 'UserManagement' and OperationType eq 'Update' and ActivityDisplayName eq 'Update user'"
Hi both properties TargetResources and Additionaldetails have multiple values, so you need to be specific when extracting multiple values for the property. I'm not sure what the delimiter for those fields are.. try the following.
Get-AzureADAuditDirectoryLogs | more | Select activityDateTime, LoggedByService, `
OperationType, InitiatedBy,`
#{name="TargetResources";expression={$_.TargetResources -join ";"}},`
#{name="Additionaldetails";expression={$_.Additionaldetails -join ";"}} |`
Export-csv -NoTypeInformation C:\temp\securitylogs.csv -NoType

Using Objects in Powershell to do command

What im trying to do is the following:
Im getting a list of all VM`s that have some set values such as being in use and NOT having Azure Benefits turned on.
What i have is that i made a tiny script to get all machines within an subscription and select on the basis mentioned above.
What i want to do with that output is do the command Update-azureVM in bulk.
Could someone help me with this ? do i need to export the values to an excel and use that sheet to do a bulk update-AzureVM
here is the code that i have setup at the moment:
$returnObj = #()
$VMs=Get-AzVm -status
foreach ($VM in $VMs)
{
$obj = New-Object psobject -Property #{
"VmSize" = $VM.HardwareProfile.VmSize;
"VmName" = $vm.Name;
"PowerState" = $vm.PowerState;
"License_Type" = $vm.LicenseType;
}
$returnObj += $obj | select VmSize, VmName, PowerState, License_Type
}
$returnObj |
Where-Object{$_.PowerState -ne "VM deallocated"} |
Where-Object{$_.License_Type -ne "Windows_Server"} |
Where-Object{$_.License_Type -ne "Windows_Client"} |
Export-Csv C:\temp\freek.csv
Thank you all in advance!

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;}

Passing PowerShell Output to CSV/Excel

I previously had asked a question regarding adding together files and folders with a common name and having them summed up with a total size (Sum of file folder size based on file/folder name). This was successfully answered with the PS script below:
$root = 'C:\DBFolder'
Get-ChildItem "$root\*.mdf" | Select-Object -Expand BaseName |
ForEach-Object {
New-Object -Type PSObject -Property #{
Database = $_
Size = (Get-ChildItem "$root\$_*\*" -Recurse |
Measure-Object Length -Sum |
Select-Object -Expand Sum ) / 1GB
}
}
This now leaves me with a list that is ordered by the 'Database' Property by default. I have attempted to use a Sort-Object suffix to use the 'Size' property with no joy. I have also attempted to use Export-Csv with confounding results.
Ideally, if I could pass the results of this script to Excel/CSV so I can rinse/repeat across multiple SQL Servers and collate the data and sort within Excel, I would be laughing all the way to the small dark corner of the office where I can sleep.
Just for clarity, the output is looking along the lines of this:
Database Size
-------- ----
DBName1 2.5876876
DBName2 4.7657657
DBName3 3.5676578
Ok, it was one pipe character that I had missed when using the Export-csv function. This resolved my problem.
$root = 'C:\DB\Databases'
Get-ChildItem "$root\*.mdf" | Select-Object -Expand BaseName |
ForEach-Object {
New-Object -Type PSObject -Property #{
Database = $_
Size = (Get-ChildItem "$root\$_*\*" -Recurse |
Measure-Object Length -Sum |
Select-Object -Expand Sum ) / 1GB
}
} | Export-Csv 'C:\Test\test.csv'

Resources