1

Is there any approach to break line in the same column in a CSV constructed by PowerShell? For example

Role     |Scope
--------------------
Role 01  |Scope 01
         |Scope 02
--------------------
Role 02  |Scope 01
         |Scope 03

I'm not sure if this is achievable. If not, what would be the supported format e.g. HTML?

[Updated] Below is my CSV object construct

class CsvObj {
   [Object] ${Role}
   [Object] ${Scope}
}

$roleList= Get-Role
$array = @()

ForEach ($role in $roleList) {
   $roleObj = [CsvObj]::new()
   $roleObj.Role = $role.Role
   $roleObj.Scope = $role.Scope
   $array += $roleObj
}
$array | Export-Csv -Path C:\file.csv

Each role may have more scopes and I'd like to group them properly.

2 Answers 2

3

In the interest of having data that's easy to process afterwards I'd suggest you instead prepare it like this:

Role     Scope
----     -----
Role 01  Scope 01
Role 01  Scope 02
Role 02  Scope 01
Role 02  Scope 03

That way you can always just group it by doing something like

Import-Csv foo.csv | group Role

whereas the alternative for the other version would be quite a bit more complicated.

You can insert line breaks in CSV cells just fine, but for this purpose I'd say they're not the best idea. If you need this for nice display purposes, then CSV is probably the wrong format and HTML may be a better option.

Sign up to request clarification or add additional context in comments.

Comments

1

Just insert newline character (`n) between scopes:

[pscustomobject]@{Role='Role 01';Scope="Scope 01`nScope 02"},
[pscustomobject]@{Role='Role 02';Scope="Scope 01`nScope 03"} | ConvertTo-Csv

4 Comments

Note: escape characters do not work in string literals (single-quotes ''), only in expanded strings (double-quotes "").
I just updated the question with my sample. Thank you. The object is dynamically appended to the CSV so I'm unsure if using 'n solves the problem
What is returned by Get-Role? (To simplify: what is the type of $roleArray?) Please run $roleArray | gm. It's declared as object.
@PawełDyl $roleList returns collection list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.