Reputation: 279
I have some data I am trying to push out to a CSV but it keeps failing. Any advice?
Import-Module ActiveDirectory
$ExportFile = "C:\T2\Test.csv"
$MacHeading = "Mac OS: "
$MACOS = Get-ADComputer -Filter 'OperatingSystem -like "MAC*"' -Properties OperatingSystem, CanonicalName | Select Name, CanonicalName, OperatingSystem
$MACOSCount = Get-ADComputer -Filter 'OperatingSystem -like "MAC*"' | Measure-Object | %{$_.Count}
$MacHeading | Export-CSV -path $ExportFile -Append
$MACOS | Export-CSV -path $ExportFile -Append
$MACOSCount | Export-CSV -path $ExportFile -Append
My error message is:
Export-CSV : Cannot append CSV content to the following file: C:\T2\Test.csv. The appended object does not have a property that corresponds to the following column: Mac OS: . To continue with mismatched properties, add the -Force parameter, and then retry the command. At C:\T2\Test.ps1:9 char:15 + $MacHeading | Export-CSV -path $ExportFile -Append + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (Mac OS: :String) [Export-Csv], InvalidOperationException + FullyQualifiedErrorId : CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell.Commands.ExportCsvCommand
Upvotes: 0
Views: 2431
Reputation: 2312
If you're willing to go without the $MacHeading
(which isn't terribly useful for a CSV), you could just do this:
Get-ADComputer -Filter 'OperatingSystem -like "MAC*"' -Properties OperatingSystem, CanonicalName |
Select Name, CanonicalName, OperatingSystem |
Export-CSV -path $ExportFile -Append -NoTypeInformation
Get-ADComputer -Filter 'OperatingSystem -like "MAC*"' |
Measure-Object | %{$_.Count} |
Out-File $ExportFile -Append -Encoding ASCII
The key is to use Out-File
instead of Out-CSV
for the items that won't really make a CSV.
Upvotes: 0
Reputation: 1026
$comps=Get-ADComputer -Filter { OperatingSystem -Like '*MAC*' } -Properties OperatingSystem,CanonicalName
Upvotes: 0
Reputation: 2904
while you can create a csv file manually it is usually cumbersome and you will have to match the column headers when you add data manually.
In your code above you start your csv by creating a csv file with one header\column 'mac os'. macos
is an objects with various properties and it does not contain a header called 'mac os' so export-csv does not know where to send the data.
also you are missing the -notypeinformation
switch to export-csv
without which the csv will contain an additional unneeded header with object type
you can look at doing something like this:
$comps = Get-ADComputer -Filter 'OperatingSystem -like "MAC*"' -Properties OperatingSystem, CanonicalName |
Select-Object @{N='MacHeading';e={'Mac OS'}},Name, CanonicalName, OperatingSystem
$comps |
ForEach-Object -Begin {$i = 0} -Process {$I++; $_ | Add-Member -Name ID -Value $i -MemberType NoteProperty -PassThru} |
Export-Csv -Path $path -NoTypeInformation
Upvotes: 1