Author Posts

December 12, 2016 at 10:11 pm

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

December 12, 2016 at 10:50 pm

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.

December 12, 2016 at 11:06 pm

... 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  ;-)
"@

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

December 12, 2016 at 11:29 pm

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

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

December 13, 2016 at 12:11 am

or like this:

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

December 13, 2016 at 2:30 pm

Thanks guys, was able to get it using

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