Home » How to Get File Size in MB Using Get-ChildItem in PowerShell

How to Get File Size in MB Using Get-ChildItem in PowerShell

To get the file size in MB using the Get-ChildItem cmdlet in PowerShell, you can use the Measure-Object cmdlet, which calculates the sum of the Length property and then divides it by 1MB.

The following method shows how you can do it with syntax.

Method 1: Get File Size in MB with the Get-ChildItem cmdlet

(Get-ChildItem -File | Measure-Object -Property Length -Sum).Sum /1MB

This example will return the file size in MB.

The following example shows how you can use this method.

How to Get File Size in MB with Get-ChildItem

You can use the Get-ChildItem cmdlet along with the -File parameter to get the file and then use the Measure-Object cmdlet to calculate the sum of the Length of the file, and then divide it by 1MB.

# specify the file path
$filePath = "C:\temp\log\my_adrecords.xlsx"

# get the file size in MB

$fileSizeinMB = (Get-ChildItem -Path $filePath -File | Measure-Object -Property Length -Sum).Sum /1MB

Write-Output "File size : $fileSizeinMB MB"

Output:

PowerShell get file size in MB with Get-ChildItem
PowerShell get file size in MB with Get-ChildItem

In this script, we defined a variable $filePath to store the file path.

The Get-ChildItem cmdlet uses the -File parameter to get only the file from the specified path $filePath and piped it to the Measure-Object cmdlet to calculate the sum of the length of the file in bytes.

We then divide the total size in bytes by 1 MB to get the file size in MB.

Finally, the Write-Output cmdlet outputs the file size in MB.

Conclusion

I hope the above article on how to get the file in MB with the Get-ChildItem cmdlet in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.