Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add Text at top of exported CSV in powershell

I’m trying to create a csv file with objectid of computers in AzureAD to be able to import into a group.
The format of the csv need to be:

version:v1.0
[memberObjectIdOrUpn]

then a list of objectid of the computers

$devices = Get-AzureADDevice -SearchString COMPUTERS
$devices = $devices.objectid | Select-Object @{n = '[memberObjectIdOrUpn]'; e = { $_ } }
$devices | Export-Csv -Path C:\temp\computers.csv -NoTypeInformation 

this will get me a list with the only issue that "version:v1.0" needs to be added on top of the file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there some way to add it before exporting the csv or do I need to do like:

@("version:v1.0") +  (Get-Content "C:\temp\computers.csv") | Set-Content "c:\temp\computers.csv"

I just feel like there’s some better way 🙂

>Solution :

I think that Convert-Csv might be easier, as it returns a string array rather than writing a file.

# get the system line separator for convenientce
$newline = [Environment]::NewLine

# set up the file header
$header = ("version:v1.0{0}" -f $newline) 

# get the device list (returns an array of strings)
$devices = Get-AzureADDevice -SearchString COMPUTERS
$devices = $devices.objectid | Select-Object @{n = '[memberObjectIdOrUpn]'; e = { $_ } } | ConvertTo-Csv -NoTypeInformation 

# write the header and your content
Set-Content -Value ($headers + ($devices -join $newline)) -Path C:\temp\computers.csv 

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading