Home > Net >  Add Text at top of exported CSV in powershell
Add Text at top of exported CSV in powershell

Time:11-23

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.

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 :)

CodePudding user response:

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 

  • Related