kekimian
kekimian

Reputation: 947

Powershell Export-Csv issue

I try to export a file in csv format from an psobject. Within of my psoobject I have a custom properties from multiples variables:

$1 = 8
$2 = 8
$props = @{

    'test' = "$1/$2"
}

$csv = New-Object -TypeName psobject -Property $props

$csv | select * | Export-Csv  C:\Users\adm-tc5190\Desktop\report\v2\test.csv 

As you can see my 'test' properties is an object from 2 variables $1 and $2. But when I export-csv in my file I get an incorrect output from my 'test' properties.

Here is the output that I get in csv file:

8-Aug but must be 8/8

Thanks in advance for help

Upvotes: 1

Views: 662

Answers (2)

Stephen Correia
Stephen Correia

Reputation: 81

If you can explain what your trying to accomplish perhaps we can provide a better way? The default behavior of Excel is to try to determine data type and 8/8 will be "translated" to a date format, this is an excel behavior and has nothing to do with Powershell or how it's treating the data.

I was successful in recreating the issue by double clicking on the csv file and opening directly in Excel. If you open a blank excel file and import, as Mathias R. Jessen mentioned below, specifying in step 3 of the text import wizard "Column data format" = text, I believe you will get the behavior you expect. It's probably more work than you want but that is how you get the result you are looking for.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

The value in the csv file is the string "8/8" - it's Excel that assumes that string to be a partial date, and formats it that way.

You can verify by looking at the actual contents of the file:

PS C:\> Get-Content "C:\Users\adm-tc5190\Desktop\report\v2\test.csv"
#TYPE Selected.System.Management.Automation.PSCustomObject
"test"
"8/8"

Instead of opening the csv file with Excel directly, you can import the data with the "Text Import Wizard" (Data tab -> Get External Data -> From Text), and specify "Text" as the data type in the last step

Upvotes: 2

Related Questions