Powershell dump in C with variable name

Good Morning,

I found a script to read out memberships of a User from active directory as per below.

       [Parameter(Mandatory = $True)]
Import-Module ActiveDirectory
If ($UserName) {
       $UserName = $UserName.ToUpper().Trim()
       $Res = (Get-ADPrincipalGroupMembership $UserName | Measure-Object).Count
       If ($Res -GT 0) {
              Write-Output "`n"
              Write-Output "The User $UserName Is A Member Of The Following Groups:"
              Write-Output "==========================================================="
              Get-ADPrincipalGroupMembership $UserName | Select-Object -Property Name, GroupScope, GroupCategory | Sort-Object -Property Name | FT -A

This has been tested and worked fine.

Please guide me on how to Save the outcome in C$ +with the usename variable.txt and then step two copy the txt file from C:\ to remote share (xcopy).

All this has to be within the same powershelll command.

Thanks in advance.
Who is Participating?
oBdAConnect With a Mentor Commented:
Sorry, but that script is, well, suboptimal.
Try it with this; you can now pass a string array with file names to save the results to. The file name(s) may contain the placeholder "{0}", which will be replaced with the UserName passed.
If the file extension is '.csv', it will save as csv, otherwise as plain text.
.\Whatever.ps1 -UserName jdoe -Path "C:\Groups_{0}.txt", "\\Server\Share\Folder\Groups_{0}.txt"

Open in new window

If you always want to save to the same locations, you can just set the Path argument in line 5 to the default values you want:
	[String[]]$Path = "C:\Groups_{0}.txt", "\\Server\Share\Folder\Groups_{0}.txt"

Open in new window

Import-Module ActiveDirectory
$groups = Get-ADPrincipalGroupMembership -Identity $UserName |
	Select-Object -Property @{n='UserName'; e={$UserName}}, Name, GroupScope, GroupCategory |
	Sort-Object -Property Name
If ($Path) {
	ForEach ($filePath In $Path) {
		$filePath = $filePath -f $UserName
		If ([IO.Path]::GetExtension($filePath) -eq '.csv') {
			$groups | Export-Csv -NoTypeInformation -Path $filePath
		} Else {
			$groups | Format-Table -AutoSize | Out-String -Width 1024 | Set-Content -Path $filePath
} Else {

Open in new window

Question answered.
All Courses

From novice to tech pro — start learning today.