Child directory sizes and owners - powershell

I'm trying to write a PowerShell script retrieving the directory size and owner on my Windows file systems. I've got two separate scripts that work independently, but I don’t know how to put them together as a single script file.
Directory Name and Size:
$startFolder = "C:\Test”
$colItems = (Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems)
{
$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum)
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}
Directory owner:
Get-ACL C:\Test
I'd like for the script to output to a CSV file.

So something along the lines of this then?
$start = "c:\temp"
$output = "C:\temp\output.csv"
Get-ChildItem $start | Where-Object{$_.PSIsContainer} | ForEach-Object{
$singleFolder = $_.FullName
$folderSize = Get-ChildItem $singleFolder -Recurse -Force | Where-Object{!$_.PSIsContainer} | Measure-Object -Property length -sum | Select-Object -ExpandProperty Sum
$folderSize = [math]::round($folderSize/1MB, 2)
$owner = Get-Acl $singleFolder | Select-Object -ExpandProperty Owner
$_ | Add-Member -MemberType NoteProperty -Name FolderSize -Value $folderSize -PassThru |
Add-Member -MemberType NoteProperty -Name Owner -Value $owner -PassThru
} | Select-Object FullName,FolderSize,Owner | Export-Csv $output -NoTypeInformation
Needed to add some extra logic in length calculation to keep folders out of the mix > Where-Object{!$_.PSIsContainer}. This should work with PowerShell 2.0 just fine.
It loops through each folder in the root of $start and for each $singleFolder calculates the size of the contents and folder owner.
The variables are then added to object through pipeline with Add-Member as the properties FolderSize and Owner. The final Select-Object is used to isolate the properties we want for the output file.
Sample
FullName FolderSize Owner
-------- ---------- -----
C:\temp\37 Place i.Bay domain\guy
C:\temp\adoc42 1103186357 domain\guy
C:\temp\Adoc72 958330505 domain\guy
Notice the empty folder. That output is sent to Export-CSV in the file $output

Related

Add a function to return folder size in Powershell [duplicate]

I have found several resources that use the following script to get folder sizes
$colItems = (Get-ChildItem $startFolder -recurse | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems)
{
$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum)
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}
The problem with that is it also lists the subdirectories ie:
c:\test\1 -- 10mb
c:\test\1\folder -- 10mb
c:\test\1\folder\deep -- 5mb
c:\test\1\folder\tuna -- 5mb
c:\test\2 -- 20bm
c:\test\2\folder -- 20mb
c:\test\2\folder\deep -- 10mb
c:\test\2\folder\tuna -- 10mb
I think you know see where I am going. What I am looking for is just the parent folder's results... SO:
c:\test\1 -- 10mb
c:\test\2 -- 20mb
How can this be accomplished with Powershell?
....
You need to get the total contents size of each directory recursively to output. Also, you need to specify that the contents you're grabbing to measure are not directories, or you risk errors (as directories do not have a Length parameter).
Here's your script modified for the output you're looking for:
$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}
This simple solution worked for me as well.
Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum
The solution posted by #Linga:
"Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum" is nice and short. However, it only computes the size of 'directory_path', without sub-directories.
Here is a simple solution for listing all sub-directory sizes. With a little pretty-printing added.
(Note: use the -File option to avoid errors for empty sub-directories)
foreach ($d in gci -Directory -Force) {
'{0,15:N0}' -f ((gci $d -File -Recurse -Force | measure length -sum).sum) + "`t`t$d"
}
Sorry to reanimate a dead thread, but I have just been dealing with this myself, and after finding all sorts of crazy bloated solutions, I managed to come up with this.
[Long]$actualSize = 0
foreach ($item in (Get-ChildItem $path -recurse | Where {-not $_.PSIsContainer} | ForEach-Object {$_.FullName})) {
$actualSize += (Get-Item $item).length
}
Quickly and in few lines of code gives me a folder size in Bytes, than can easily be converted to any units you want with / 1MB or the like.
Am I missing something? Compared to this overwrought mess it seems rather simple and to the point. Not to mention that code doesn't even work since the called function is not the same name as the defined function. And has been wrong for 6 years. ;)
So, any reasons NOT to use this stripped down approach?
This is similar to https://stackoverflow.com/users/3396598/kohlbrr answer, but I was trying to get the total size of a single folder and found that the script doesn't count the files in the Root of the folder you are searching. This worked for me.
$startFolder = "C:\Users";
$totalSize = 0;
$colItems = Get-ChildItem $startFolder
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$totalSize = $totalSize + $subFolderItems.sum / 1MB
}
$startFolder + " | " + "{0:N2}" -f ($totalSize) + " MB"
This is something I wind up looking for repeatedly, even though I wrote myself a nice little function a while ago. So, I figured others might benefit from having it and maybe I'll even find it here, myself. hahaha
It's pretty simple to paste into your script and use. Just pass it a folder object.
I think it requires PowerShell 3 just because of the -directory flag on the Get-ChildItem command, but I'm sure it can be easily adapted, if need be.
function Get-TreeSize ($folder = $null)
{
#Function to get recursive folder size
$result = #()
$folderResult = "" | Select-Object FolderPath, FolderName, SizeKB, SizeMB, SizeGB, OverThreshold
$contents = Get-ChildItem $folder.FullName -recurse -force -erroraction SilentlyContinue -Include * | Where-Object {$_.psiscontainer -eq $false} | Measure-Object -Property length -sum | Select-Object sum
$sizeKB = [math]::Round($contents.sum / 1000,3) #.ToString("#.##")
$sizeMB = [math]::Round($contents.sum / 1000000,3) #.ToString("#.##")
$sizeGB = [math]::Round($contents.sum / 1000000000,3) #.ToString("#.###")
$folderResult.FolderPath = $folder.FullName
$folderResult.FolderName = $folder.BaseName
$folderResult.SizeKB = $sizeKB
$folderresult.SizeMB = $sizeMB
$folderresult.SizeGB = $sizeGB
$result += $folderResult
return $result
}
#Use the function like this for a single directory
$topDir = get-item "C:\test"
Get-TreeSize ($topDir)
#Use the function like this for all top level folders within a direcotry
#$topDir = gci -directory "\\server\share\folder"
$topDir = Get-ChildItem -directory "C:\test"
foreach ($folderPath in $topDir) {Get-TreeSize $folderPath}
My proposal:
$dir="C:\temp\"
get-childitem $dir -file -Rec | group Directory | where Name -eq $dir | select Name, #{N='Size';E={(($_.Group.Length | measure -Sum).Sum / 1MB)}}
from sysinternals.com with du.exe or du64.exe -l 1 .
or 2 levels down:
**du -l 2 c:**
Much shorter than Linux though ;)
At the answer from #squicc if you amend this line: $topDir = Get-ChildItem -directory "C:\test" with -force then you will be able to see the hidden directories also. Without this, the size will be different when you run the solution from inside or outside the folder.
I used the great answer of #kohlbrr and improved it a bit. I also turned it into a function you can put in your $PROFILE. This outputs three properties instead of just text: Name, Size (which is a string output of the size converted to MB), and Value which is the raw size value you can use with | sort value
function Get-DirectorySize([string] $rootFolder) {
$colItems = Get-ChildItem $rootFolder | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems) {
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
[PSCustomObject]#{ Name=$i.Fullname; Size="{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"; Value=$subFolderItems.sum }
}
}
The following script provides file sizes from a directory(not going deep) and sizes in bytes.(give your path in $($args[0]) in both the scripts)
Get-ChildItem -Path "$($args[0])" -Recurse -Depth 0 -file| select Length,LastWriteTime,FullName | Export-Csv .\FileAndFolderSizes.csv -NoTypeInformation
The following script provides the folder sizes(depth 0 ) in bytes within the given directory.
$array= #()
Get-ChildItem -Path "$($args[0])" -Recurse -Depth 0 | Where-Object { $_.PSIsContainer } |
ForEach-Object {
$obj = New-Object PSObject
$Size = [Math]::Round((Get-ChildItem -Recurse $_.FullName | Measure-Object Length -Sum -ErrorAction SilentlyContinue).Sum, 2)
$obj |Add-Member -MemberType NoteProperty -Name "FullName" $_.FullName
$obj |Add-Member -MemberType NoteProperty -Name "LastWriteTime" $_.LastWriteTime
$obj |Add-Member -MemberType NoteProperty -Name "Length" $Size
$array +=$obj
}
$array | select Length,LastWriteTime,FullName | Export-Csv .\FileAndFolderSizes.csv -NoTypeInformation -Append
Output is as follows
"Length","LastWriteTime","FullName"
"593408","2/17/2022 10:51:01 PM","C:\a_appli\Partners_Ref\Client64_Rws2\compresslayer.dll"
"286720","2/9/2021 11:52:18 PM","C:\a_appli\Partners_Ref\Client64_Rws2\fdsrtd.dll"
"589312","6/19/2019 10:18:41 PM","C:\a_appli\Partners_Ref\Client64_Rws2\FdswCli.dll"
"13658276","3/18/2022 9:52:16 AM","C:\a_appli\Partners_Ref\Client64_Rws2\PartnersTemplateBuilder"
Interesting how powerful yet how helpless PS can be in the same time, coming from a Nix learning PS. after install crgwin/gitbash, you can do any combination in one commands:
size of current folder:
du -sk .
size of all files and folders under current directory
du -sk *
size of all subfolders (including current folders)
find ./ -type d -exec du -sk {} \;

Generate a report of entire D: Drive using PowerShell

I am new to PowerShell scripting. For one of my School project I need to generate a report of the entire D Drive. I need to list all the folders sorted according to the size
Summary of the work I have done so far:
I have installed a PowerShell module from this website
https://www.gngrninja.com/script-ninja/2016/5/24/powershell-calculating-folder-sizes
using Install-Module PSFolderSize
After installing if I run the command Get-FolderSize I'm getting the FolderSize for the path I'm running from. The foldersize is not running for all the folders in the directory.
I am facing difficulty traversing through all the folders.
Expected Output:
+-------------+--------------+--------------+-----------+-----------------------+-----------+
| FolderName | Size(Bytes) | Size(MB) | Size(GB) | FullPath | HostName |
+-------------+--------------+--------------+-----------+-----------------------+-----------+
| Disney | 454545448889 | 433488.32024 | 423.32844 | D:\Videos\Disney | localhost |
| Universal | 25454544884 | 24275.34569 | 23.70639 | D:\Videos\Universal | localhost |
| Fox Studios | 8803063287 | 8395.25536 | 8.19849 | D:\Videos\Fox Studios | localhost |
+-------------+--------------+--------------+-----------+-----------------------+-----------+
Can anyone help me where to start?
I would use other tools (like TreeSize) for creating reports like this because of the speed and long filename problematics.
However you could solve your task with the following powershell command without downloading an other Module.
For each subfolder inside your D:\ you have to receive your required data.
You have to calculate the size of each directory by looking for each file Get-ChildItem -Path $Folder.FullName -Recurse -Force and sum up the lenght of all files.
Here you can use the Measure-Object -Property Length -Sum. Depending on the directory size this task will take some time.
Take a look here if you struggle with long file name issues.
After collection and adding all data to an output variable use Select-Object -Property 'FolderName', 'Size(Bytes)', 'Size(MB)', 'Size(GB)', 'FullPath', 'HostName' for sorting the header order.
The command Sort-Object -Property 'Size(Bytes)', 'FolderName' will sort the output depending on the folder size and name.
For a nice looking output use Format-Table.
[System.String]$Path = 'D:\'
[PSCustomObject[]]$Output = #()
foreach ($Folder in (Get-ChildItem -Path $Path -Directory))
{
[System.Int64]$Size = (Get-ChildItem -Path $Folder.FullName -Recurse -Force | Measure-Object -Property Length -Sum).Sum
[System.Collections.Hashtable]$Hashtable = #{
'FolderName' = $Folder.Name
'Size(Bytes)' = $Size
'Size(MB)' = $Size / 1MB
'Size(GB)' = $Size / 1GB
'FullPath' = $Folder.FullName
'HostName' = $env:COMPUTERNAME
}
$Output += New-Object -TypeName 'PSCustomObject' -Property $Hashtable
}
$Output | `
Select-Object -Property 'FolderName', 'Size(Bytes)', 'Size(MB)', 'Size(GB)', 'FullPath', 'HostName' | `
Sort-Object -Property 'Size(Bytes)', 'FolderName' | `
Format-Table
[System.String]$Path = 'D:\'
[PSCustomObject[]]$Output = #()
foreach ($Folder in (Get-ChildItem -Recurse $Path | Where-Object { $_.PSIsContainer }))
{
[System.Int64]$Size = (Get-ChildItem -Path $Folder.FullName -Recurse -Force | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum
[System.Collections.Hashtable]$Hashtable = #{
'FolderName' = $Folder.Name
'Size(Bytes)' = $Size
'Size(MB)' = [Math]::Round($Size / 1MB ,2)
'Size(GB)' = [Math]::Round($Size / 1GB,2)
'FullPath' = $Folder.FullName
'HostName' = $env:COMPUTERNAME
}
$Output += New-Object -TypeName 'PSCustomObject' -Property $Hashtable
}
$Output | `
Select-Object -Property 'FolderName', 'Size(Bytes)', 'Size(MB)', 'Size(GB)', 'FullPath', 'HostName' | `
Sort-Object -Property 'Size(Bytes)' , 'FolderName' -Descending | `
Format-Table

Exporting Results of Script to CSV

I've been searching for a script that simply lists folders in a share and their size. I found the following but I'm getting hung up on how to export the output I'm seeing to an easy to read CSV. It amazes me how something so simple has turned into something difficult. Suggestions welcome!
$colItems = Get-ChildItem "C:\Users\user.name\Desktop" | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}
Based on your script:
## C:\Users\UserName\Desktop\Test\SO_50359947.ps1
$colItems = Get-ChildItem "$($Env:USERPROFILE)\Desktop" |
Where-Object {$_.PSIsContainer} | Sort-Object
$data = ForEach ($i in $colItems){
$subFolderItems = Get-ChildItem $i.FullName -recurse -force -ea 0|
Where-Object {!$_.PSIsContainer} |
Measure-Object -Property Length -sum | Select-Object Sum
[PSCustomObject]#{
Folder = $i.FullName
Size = "{0,10:N2} MB" -f ($subFolderItems.sum / 1MB)
}
}
$data
#$data | Export-Csv "$($Env:USERPROFILE)\Desktop\your.csv" -NoType
Sample output (on a different tree)
> $data
Folder Size
------ ----
Q:\test\2018\03 0,37 MB
Q:\test\2018\04 0,83 MB
Q:\test\2018\05 383,57 MB
Uncomment the last line to write to a csv file.
Here is one way using custom objects:
Get-ChildItem "$home\Desktop" -Directory |
ForEach-Object {
$contents = Get-ChildItem -Path $_.FullName -Recurse
[PsCustomObject]#{
FolderName = $_.Name
SizeMB = [Math]::Round(($contents | Where-Object PsIsContainer -eq $false | Measure-Object -property Length -Sum).Sum / 1MB,2)
SubFolders = ($contents | Where-Object PsIsContainer -eq $true | Measure-Object).Count
Files = ($contents | Where-Object PsIsContainer -eq $false | Measure-Object).Count
}
}
This gives output like this:
FolderName SizeMB SubFolders Files
---------- ------ ---------- -----
Folder1 438.38 19 124
Folder2 34925.72 306 3779
To send this to CSV, simply append the following after the last bracket:
| Export-Csv "$home\Desktop\Folders.csv" -NoTypeInformation
There's a couple ways to do this, but I think the least confusing would be to simply add that information to the item using Add-Member. Then output the desired data via Export-Csv.
$colItems = Get-ChildItem "C:\Users\user.name\Desktop" |
Where-Object {$_.PSIsContainer -eq $true} |
Sort-Object |
%{ Add-Member -InputObject $_ -NotePropertyName 'FolderSize' -NotePropertyValue (Get-ChildItem $_.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object -ExpandProperty Sum) -PassThru}
$colItems | Select FullName,FolderSize | Export-Csv -NoType
Please assign to some variable after getting all the file details from the desktop/any location and create the excel
$subFolderItems = Get-ChildItem "$home\Desktop" -Directory |
ForEach-Object {
$contents = Get-ChildItem -Path $_.FullName -Recurse
[PsCustomObject]#{
FolderName = $_.Name
SizeMB = [Math]::Round(($contents | Where-Object PsIsContainer -eq $false | Measure-Object -property Length -Sum).Sum / 1MB,2)
SubFolders = ($contents | Where-Object PsIsContainer -eq $true | Measure-Object).Count
Files = ($contents | Where-Object PsIsContainer -eq $false | Measure-Object).Count
}
}
$subFolderItems | out-file C:\Users\thiyagu.a.selvaraj\Desktop\PowerShell\FileSizeOutput.xls
In my opinion, using CSV for your use case isn't the best plan because (in my folder) there are files that are over 1000 MB, so csv will break up some file sizes. To make a tab delimited file, which can just as easily be parsed by most systems, simply modify your scripts output string.
I changed the -- to a tab character, and added an output at the end of the line
"{0}`t{1:N2} MB" -f $i.fullname,($subFolderItems.sum / 1MB) >> output.csv
The final script is below; you will probably need to change output.csv to your prefered output file location.
$colItems = Get-ChildItem "C:\Users\user.name\Desktop" | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
"{0}`t{1:N2} MB" -f $i.fullname,($subFolderItems.sum / 1MB) >> output.csv
}
If you don't insist on using pure powershell, on Windows 10 (sufficiently new) you can just call bash:
bash -c "du -h | sed 's/\s\+/,/'"
To show how it affects the resulting csv, a longer example:
bash -c "du -m | sed 's/\([0-9]\+\)\s\+\(.*\)/\1MB,\2/'"

Powershell: Using Get-ChildItem with variables

I am writing a script that will iterate through folders, grabbing substrings of the folder names as variable values, and then iterate through the log files in each of the folders and get some data out of the log files for output to a .csv file. Where I am running into an issue is with the use of Get-ChildItem with variables I have already set. When I run this line by itself, it does not provide any value:
#running this to see the value of $files
$files = Get-ChildItem $_.FullName $folder
$files does not then contain any value.
Here is the entire portion of the script, for reference and context:
#get all folders from the Logs directory
$folders = Get-ChildItem "C:\Temp\MPOS\Logs"
#iterate through each folder
foreach ($folder in $folders) {
#set substrings of the folder name to variables
$storeNumber = $folder.Name.Substring(2,3)
$date = $folder.Name.Substring(9,7)
#get all files from the current folder being evaluated
$files = Get-ChildItem $_.FullName $folder
#iterate through each file in the current folder
foreach ($file in $files) {
#set substring of the file name to a variable
$registerNumber = $file.Name.Substring(12,4)
#get content of the file
$logfileContent = Get-Content $file
#look for all matches of the string "TransactionNumber"
$transactions = Select-String -InputObject $logfileContent -Pattern "TransactionNumber" -AllMatches
#count number of matches from above
$transactionCount = $transactions.Matches.Count
#below info is creating the object for the .csv
$transObject = New-Object PSObject
$transObject | Add-Member -MemberType NoteProperty -Name "StoreNumber" -Value $storeNumber
$transObject | Add-Member -MemberType NoteProperty -Name "Sales Date" -Value $date
$transObject | Add-Member -MemberType NoteProperty -Name "RegisterNumber" -Value $registerNumber
$transObject | Add-Member -MemberType NoteProperty -Name "Transactions" -Value $transactionCount
$resultsArray += $transObject
}
}
$resultsArray | Export-Csv C:\Temp\MPOS\MPOSTransactions.csv -NoTypeInformation
Edited code below - changed to read $folder.FullName - working now!
$resultsArray = #()
$folders = Get-ChildItem "C:\Temp\MPOS\Logs"
foreach ($folder in $folders) {
$storeNumber = $folder.Name.Substring(2,3)
$date = $folder.Name.Substring(9,7)
$files = Get-ChildItem $folder.FullName
foreach ($file in $files) {
$registerNumber = $file.Name.Substring(12,4)
$logfileContent = Get-Content $file.FullName
$transactions = Select-String -InputObject $logfileContent -Pattern "TransactionNumber" -AllMatches
$transactionCount = $transactions.Matches.Count
$transObject = New-Object PSObject
$transObject | Add-Member -MemberType NoteProperty -Name "StoreNumber" -Value $storeNumber
$transObject | Add-Member -MemberType NoteProperty -Name "Sales Date" -Value $date
$transObject | Add-Member -MemberType NoteProperty -Name "RegisterNumber" -Value $registerNumber
$transObject | Add-Member -MemberType NoteProperty -Name "Transactions" -Value $transactionCount
$resultsArray += $transObject
}
}
$resultsArray | Export-Csv C:\Temp\MPOS\MPOSTransactions.csv -NoTypeInformation
I had this exact issue, but I found out in my case I was trying to load a variable by piping in a value that also was using Format-Table command.
Example: (this worked)
$GetMostRecentFile = $GetLatestFile = Get-ChildItem -Force -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $.LastWriteTime.Date -lt (Get-Date).Date -and $.Name -ne 'Thumbs.db' -and $_.Name -ne '.DS_Store'} | Sort LastWriteTime -Descending | Select-Object -First 1 LastWriteTime,FullName,Length
(this didn't work)
$GetLatestFile = Get-ChildItem -Force -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $.LastWriteTime.Date -lt (Get-Date).Date -and $.Name -ne 'Thumbs.db' -and $_.Name -ne '.DS_Store'} | Sort LastWriteTime -Descending | Select-Object -First 1 LastWriteTime,FullName,Length | Format-Table -Wrap
Because I'd been using Format-Table as part of my commands to explore this data and build my queries, I forgot that if you pipe this (with FT) to a variable, the variable won't have the details.
In my case above, I needed to pull $GetMostRecentFile.FullName and $GetMostRecentFile.LastWriteTime pulled into another array. But when I was piping with FT, there was not $GetMostRecentFile.FullName. When I remove

File and folder count

There is a folder on the remote server which has various subfolders in it. It is completely nested. I would like to:
Prepare an HTML report which contains folder name.
For every folder it should also record the file count.
The code needs to append the HTML file which is already created.
Columns required: Folder name, Folder Path, File Count
Below is the code snippet which is part of my main script. I am fairly new to PowerShell.
Can some one please help?
$server_dir = "D:\Data\Inbox"
$does_dir_e = (Test-Path $server_dir)
if($does_dir_e)
{
$fso = New-Object -com "Scripting.FileSystemObject"
$f = $fso.GetFolder($server_dir)
foreach($folder in $f.subfolders)
{
$fcount = $((Get-ChildItem $folder.Path).count)
$fname = $folder.name | Convertto-HTML -Fragment >> C:\Temp\Server.html
}
}
You don't actually say what isn't working for you, but the following script should get you started.
The outer loop recurses through the folders (PSIsContainer) means it is a folder.
The inner loop counts the number of files in each folder using measure-object, we filter out folders from this count to give us just the file count.
$path = "D:\Data\Inbox"
# Enumerate the given path recursively
Get-ChildItem -Path $path -Recurse | Where-Object {$_.PSIsContainer} | %{
# Add a user-defined custom member with a value of the filecount this
# time not recursively (using measure object)
$_ | add-member -membertype noteproperty -name FileCount -value (Get-ChildItem -Path $_.Fullname |
Where-Object {!$_.PSIsContainer} |
Measure-Object).Count
# Output the required values
$_ | select Name, FullName, FileCount | ConvertTo-Html -Fragment
}
Is this what you want? I haven't used the HTML cmdlet before, so be aware it's ugly : )
$server_dir = 'D:\Data\Inbox'
if(Test-Path $server_dir)
{
$folders = Get-ChildItem $server_dir -Recurse | where {$_.PSIsContainer}
$output = #()
foreach($folder in $folders)
{
$fname = $folder.Name
$fpath = $folder.FullName
$fcount = Get-ChildItem $fpath | where {!$_.PSIsContainer} | Measure-Object | Select-Object -Expand Count
$obj = New-Object psobject -Property #{FolderName = $fname; FolderPath = $fpath; FileCount = $fcount}
$output += $obj
}
#Output to HTML
$output | ConvertTo-Html -Fragment >> 'C:\Temp\Server.html'
}