Avatar of aravind anche
aravind anche
Flag for United States of America asked on

Powershell Question

Hello experts,

I have a script which works good and get me almost what I need.  it output the data into csv file. but it shows size in KB. I want to change that in MB. Also how to include headers into CSV?

I tried adding MB at the end of measure command, but size less than 1 GB it shows 1

Any suggestions?

Regards

Powershell
 $File = "C:\Data.csv"  
  $Exclusions = ("Administrator", "Default", "Public")  
 $Profiles = Get-ChildItem -Path $env:SystemDrive"\Users" | Where-Object { $_ -notin $Exclusions }  
 $AllProfiles = @()  
 foreach ($Profile in $Profiles) {  
      $object = New-Object -TypeName System.Management.Automation.PSObject  
          $FolderSizes = [System.Math]::Round("{0:N2}" -f ((Get-ChildItem ($Profile.FullName + '\Documents'), ($Profile.FullName + '\Desktop') -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB))  
      $object | Add-Member -MemberType NoteProperty -Name ComputerName -Value $env:COMPUTERNAME.ToUpper()  
      $object | Add-Member -MemberType NoteProperty -Name Profile -Value $Profile  
      $Object | Add-Member -MemberType NoteProperty -Name Size -Value $FolderSizes  
      $AllProfiles += $object  
 }  
  [string]$Output = $null  
 foreach ($Entry in $AllProfiles) {  
      [string]$Output += $Entry.ComputerName + ',' + $Entry.Profile + ',' + $Entry.Size + [char]13  
 }  
 $Output = $Output.Substring(0,$Output.Length-1)  
  Do {  
      Try {  
           $Output | Out-File -FilePath $File -Encoding UTF8 -Append -Force  
           $Success = $true  
      } Catch {  
           $Success = $false  
      }  
 } while ($Success = $false) 

Open in new window

Powershell

Avatar of undefined
Last Comment
aravind anche

8/22/2022 - Mon
Jacob Durham

This isn't the whole script. Where's the rest?
aravind anche

ASKER
Sorry my bad edited it
oBdA

You're trying to round a string ...
And there's no need to manually construct a csv; that's what Export-Csv is for.
Try it like this:
$File = 'C:\Data.csv'

$Exclusions = 'Administrator', 'Default', 'Public'
Get-ChildItem -Path "$($env:SystemDrive)\Users" -Directory | Where-Object {$Exclusions -notcontains $_.Name} | ForEach-Object {
	Try {
		$out = [PSCustomObject]([ordered]@{
			'ComputerName' = $env:COMPUTERNAME
			'Profile' = $_.Name
			'Size (MB)' = $null
			'Error' = $null
		})
		$folderSize = (Get-ChildItem -Path "$($_.FullName)\Documents", "$($_.FullName)\Desktop" -File -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum
		$out.'Size (MB)' = '{0:N2}' -f ($folderSize / 1MB)
	} Catch {
		$out.Error = $_.Exception.Message
	}
	$out
} | Export-Csv -NoTypeInformation -Path $File

Open in new window


Edit: Fixed issue with "Documents" path.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
aravind anche

ASKER
Thanks for the reply

I ran the script and the data is not correct

on my PC, I ran i got the below result in the csv
Size (MB)
16,116.03
1.26
0

But actual size are
21.0 GB
787 MB
154 MB

Any suggestions?
oBdA

Sorry, that was a single quote that somehow sneaked into the "Documents" path
It's fixed above, so download again, or just remove the single quote directly after "Documents" in line 12:
... "$($_.FullName)\Documents'"
                             ^

Open in new window

aravind anche

ASKER
Thanks alot,

Also, what to include to add another column to add total size of user profile? Total size if it is in GB or MB

ComputerName      Profile      Size (MB)      Total Size
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
oBdA

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
aravind anche

ASKER
Sorry I came back with other requirement, is there any way I can include profile created date
oBdA

$File = 'C:\Data.csv'  

$Exclusions = 'Administrator', 'Default', 'Public'
Get-ChildItem -Path "$($env:SystemDrive)\Users" -Directory | Where-Object {$Exclusions -notcontains $_.Name} | ForEach-Object {
	Write-Host "Processing $($_.Name) ..."
	Try {
		$out = [PSCustomObject]([ordered]@{
			'ComputerName' = $env:COMPUTERNAME
			'Profile' = $_.Name
			'Total Size (MB)' = $null
			'Documents Size (MB)' = $null
			'Created' = (Get-Item -Path $_.FullName).CreationTime.ToString('yyyy-MM-dd HH:mm:ss')
			'Error' = $null
		})
		$totalSize = (Get-ChildItem -Path $_.FullName -File -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum
		$documentsSize = (Get-ChildItem -Path "$($_.FullName)\Documents", "$($_.FullName)\Desktop" -File -Recurse -ErrorAction Stop | Measure-Object -Property Length -Sum).Sum
		$out.'Total Size (MB)' = '{0:N2}' -f ($totalSize / 1MB)
		$out.'Documents Size (MB)' = '{0:N2}' -f ($documentsSize / 1MB)
	} Catch {
		$out.Error = $_.Exception.Message
	}
	$out
} | Export-Csv -NoTypeInformation -Path $File

Open in new window

aravind anche

ASKER
Thanks,
this can be used on remote machine as well right if we change 'ComputerName' = $env:COMPUTERNAME
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
oBdA

No. That's just a string taken from an environment variable, it has nothing to do with remote access.
You'd need to set the initial path in line 4 to "\\remotemachine\c$\Users" and adjust the computer name in line 8 accordingly.
aravind anche

ASKER
Thanks,

I changed the script it didnt work
$File = 'C:\data.csv'  

$Exclusions = 'Administrator', 'Default', 'Public'
#Get-ChildItem -Path "$($env:SystemDrive)\Users" -Directory | Where-Object {$Exclusions -notcontains $_.Name} | ForEach-Object {
Get-ChildItem -Path "\\remotemachine\c$\Users" -Directory | Where-Object {$Exclusions -notcontains $_.Name} | ForEach-Object {

	Write-Host "Processing $($_.Name) ..."
	Try {
		$out = [PSCustomObject]([ordered]@{
			'ComputerName' = remote machine
			'Profile' = $_.Name
			'Total Size (MB)' = $null
			'Documents Size (MB)' = $null
			'Created' = (Get-Item -Path $_.FullName).CreationTime.ToString('yyyy-MM-dd HH:mm:ss')
			'Error' = $null
            'Total User folder size' = "{0:N2} MB" -f ((Get-ChildItem C:\users\ -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB)
		})
		$totalSize = (Get-ChildItem -Path $_.FullName -File -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum
		$documentsSize = (Get-ChildItem -Path "$($_.FullName)\Documents", "$($_.FullName)\Desktop" -File -Recurse -ErrorAction Stop | Measure-Object -Property Length -Sum).Sum
		$out.'Total Size (MB)' = '{0:N2}' -f ($totalSize / 1MB)
		$out.'Documents Size (MB)' = '{0:N2}' -f ($documentsSize / 1MB)
	} Catch {
		$out.Error = $_.Exception.Message
	}
	$out
} | Export-Csv -NoTypeInformation -Path $File

Open in new window


In the script, i gave machine name in place of the remote machine, in the excel it has the user account which does not exist and the machine name is not correct as well, it has the machine name on which I am currently working on
PFA screen shot

error column in excel: The term 'aafwscpknxg2' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Regards
AJ
oBdA

You did not put quotes around the remote computer name in line 10.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
aravind anche

ASKER
Ya i saw that after posting the before comment, Thanks oBdA