Leading space on Set-Content

I’m trying to create a report, it works fine but there is a leading space on my $users variable when putting it into a .txt file.
Below is the code I’m using and below that is an example of the report generated.

Why is there a leading space and how can I resolve this?

$users = (Get-ADGroupMember $selected).name | ForEach-Object{"$_`r`n"}
		
		Set-Content c:\Users\test\Desktop\$($selected).txt "Shared Permissions Report`r`n`r`nShare Server: vMIBFILESTORE`r`nTotal Shares: $($datagridview1.RowCount)`r`nDirectory Filter: $deep`r`nGroup/User: $selected`r`nDate: $(get-date)`r`nGroup Members`r`n*****************************`r`n$users`r`n`r`nPermissions`r`n*****************************"

This outputs like…

Shared Permissions Report

Share Server: ShareServer
Total Shares: 1371
Directory Filter: 
Group/User: cash management
Date: 12/12/2016 16:01:11
Group Members
*****************************
Julie 
 Mark 
 Tony 
 Monica 

\\ShareServer\Share\Operations\Cash Management
\\ShareServer\Share\Operations\Cash Management\Data
\\ShareServer\Share\Operations\Cash Management\Data\CIS

Like this your code looks pretty unclear and is hard to read and hard to debug. Why dont you try something like this …


$OutputFile = ‘OutputFilePath’
“Shared Permissions Report`n” | Out-File -FilePath OutputFile -Append "Share Server: '($ShareServer)’" | Out-File -FilePath $OutputFile -Append
" * 35 | Out-File -FilePath OutputFile -Append "Total Shares: ($datagridview1.RowCount)" | Out-File -FilePath $OutputFile -Append
“Directory Filter: $deep” | Out-File -FilePath $OutputFile -Append
“Group/User: $selected” | Out-File -FilePath OutputFile -Append "Date: (get-date)" | Out-File -FilePath $OutputFile -Append
“Group Members”| Out-File -FilePath $OutputFile -Append
"
” * 35 | Out-File -FilePath $OutputFile -Append
$users | Out-File -FilePath $OutputFile -Append
… and so on

… yes, it is more code but I think it is much easier to maintain.

… or … even better:


$OutputFile = ‘OutputFilePath’

OutputString = @" Shared Permissions Report`n Share Server: '(ShareServer)' (’’ * 35 )
Total Shares: ‘$(datagridview1.RowCount)' Directory Filter: '(deep)' Group/User: '(selected)' Date: '(get-date)’
Group Members
$(’
’ * 35 )
$users
… and so on and on and on :wink:
"@

$OutputString | Out-File -FilePath $OutputFile -Append

To answer your question about the space, I would try the following:

$users = (Get-ADGroupMember $selected).name | ForEach-Object{"$_.Trim()`r`n"}

or like this:

$users = ((Get-ADGroupMember $selected).name ) -join "`n"

Thanks guys, was able to get it using

$users = ((Get-ADGroupMember $selected).name ) -join "`r`n"