PowerShell - Add imported csv column into newly exported csv - azure

I was hoping someone can help me out. I am trying to get the date a license was assigned to a user and export it to a new csv. The import csv contains the UserPrincipalName. I was able to narrow down to only show which license I want but having the UPN show next to the license/date would complete this script. Thanks in advance
$getusers = Import-csv -Path 'C:\test\userlist.csv'
foreach ($user in $getusers) {
(Get-AzureADUser -searchstring $User.UserPrincipalName).assignedplans | where {$_.Service -eq 'MicrosoftOffice'} | Select-Object Service,AssignedTimeStamp |
Export-CSV -Path "C:\test\userlist-export.csv" -notypeinformation
}

I would do it this way, first querying the user and storing it in a variable and then filter the AssignedPlans where Service = MicrosoftOffice. To construct the objects you can use [pscustomobject]. Worth noting, the call to Export-Csv should be the last statement in your pipeline (it shouldn't be inside the loop), otherwise you would be replacing the Csv with a new value on each loop iteration instead of appending data.
Import-Csv -Path 'C:\test\userlist.csv' | ForEach-Object {
$azUser = Get-AzureADUser -ObjectId $_.UserPrincipalName
foreach($plan in $azUser.AssignedPlans) {
if($plan.Service -eq 'MicrosoftOffice') {
[pscustomobject]#{
UserPrincipalName = $azUser.UserPrincipalName
Service = $plan.Service
AssignedTimeStamp = $plan.AssignedTimeStamp
}
}
}
} | Export-Csv "C:\test\userlist-export.csv" -NoTypeInformation

Related

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

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

Issue with export-csv no data?

In my report when I remove the export-csv portion the data is presented correctly onscreen, when I add in the export-csv no data is exported but the file is created. Below is my script along with what the data looks like when script is running (modified) of what the data looks like.
#Get all DHCP Servers
$ServerList = (Get-Content -Path "\\termserv\DHCPServers.txt")
foreach ($server in $serverlist)
{
#Get the scopes from each serve
Get-DHCPServerv4Scope -ComputerName $server | select ScopeID |
#Get the lease information for each scope
ForEach-Object {Get-DHCPServerv4Lease -ScopeId $_.ScopeId -ComputerName
$server -AllLeases |
where {$_.AddressState -like "*Reservation"} | Select-Object
$server,ScopeId,IPAddress,HostName,ClientID,AddressState | Export-
Csv "\\termserv\d$\term\User\Reservations1.csv"
}
}
What the data looks like when exported without export-csv
NOPEDH01 :
ScopeId : 000.11.2.3
IPAddress : 111.22.3.444
HostName : NOPE00112233
ClientID : 00-11-22-33-44-55
AddressState : ActiveReservation
NOPEDH01 :
ScopeId : 000.11.2.3
IPAddress : 111.22.3.445
HostName : NOPE0011223344
ClientID : 00-11-22-33-44-56
AddressState : ActiveReservation
Update: Tried that and still nothing, when I run a modified version of the script locally on my DH servers it functions correctly, but I'm looking at almost 100 DH servers in my environment, see below
Get-DHCPServerV4Scope | ForEach {
Get-DHCPServerv4Lease -ScopeID $_.ScopeID -AllLeases | where
{$_.AddressState -like '*Reservation'}
} | Select-Object ScopeId,IPAddress,HostName,ClientID,AddressState | Export-
Csv "\\termserv\d$\term\$($env:COMPUTERNAME)-Reservations1.csv" -
NoTypeInformation
This is a representation of what you are doing:
Foreach ($Server in $ServerList)
{
Foreach ($Scope in $ScopeList)
{
$Data | Export-csv -Path FileName.csv
}
}
In doing so you are exporting data [(Total Servers) x (Total Scopes per server)] times which is a lot of I/O operations. It is just a logistics issue. You could collect the entire information into a table object before exporting. But that decision is up to you and your particular business needs.
The real issue, however, is that you are doing the export into the same file which essentially over writes whatever you have written before without telling it not to. So only the last export remains which I suspect is somehow blank.
Try using the -Append switch when you export.
$Data | Export-csv -Path FileName.csv -NoTypeInformation -Append
Also I noticed you are using $server variable in the select-object cmdlet where you should only be using the object's property names and not variable names. I do not know if that returns anything as the cmdlet would not know what to do with it, which could also be contributing to the problem.
According to your code you are using Export-Csv within a foreach-object. Generally Export-csv creates a csv file with new data. If data is already present in the csv file then it will overwrite the existing data with new one.
So instead of using
Export-Csv "\\termserv\d$\term\User\Reservations1.csv"
You cand use
Export-Csv "\\termserv\d$\term\User\Reservations1.csv" -Force -Append -NoTypeInformation
Here -Append will append the data in the csv file. Not overwrites.

Fill in column into excel with powershell

I'm trying to create a report which will get two sets of information, Group name and domain. The problem is that the information will be output into one column instead of two for example:
Group Member Domain
thisIsGroupMember,Domain
but I want it to be like this:
Group Member Domain
thisIsGroupMember, Domain
I also try export-csv but the created csv file only show
Length
32
Here's my code:
$appName = $findone.properties.name
$domain = (($findone.properties.adspath -split ',')[3].substring(3)
$inputstring = "$appName,$domain"
out-file -FilePath "C:\Test\Result.csv" -append -inputObject $inputstring
If your code iterates through a list of objects pulled from AD you can use something like this:
# your foreach code
{
...
$appName = $findone.properties.name
$domain = (($findone.properties.adspath -split ',')[3].substring(3)
$output += ,(New-Object -TypeName psobject -Property #{"Group Member"=$appName;"Domain"=$domain})
}
$output | Export-Csv "C:\Test\Result.csv"
$output is an array of objects being created on the fly with $appName and $domain values. It will then nicely export to a csv after all AD objects are processed.

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