Including and ID and Parent ID in Powershell File Inventory - powershell

I have a powershell script that performs and inventory of a fileshare. I want to know how to add ID to each line in the csv file and also a parent ID to line in the csv.
I am new to Powershell but worked out how to get the inventory script working.
Here is the code.
#Set-ExecutionPolicy Unrestricted
$SourcePath = "G:\My Drive"
$DestinationCSVPath = "e:\G Drive Inventory 20180611.csv" #Destination for Temp CSV File
$CSVColumnOrder = 'Path', 'IsDIR', 'Directory', 'FileCount', 'Parent', 'Name', 'CreationTime', 'LastAccessTime', 'LastWriteTime', 'Extension', 'BaseName', 'B'
#, 'Root', 'IsReadOnly', 'Attributes', 'Owner', 'AccessToString', 'Group' #, #'MD5', #'SHA1' #Order in which columns in CSV Output are ordered
#FOLDERS ONLY
#$SourcePathFileOutput = Get-ChildItem $SourcePath -Recurse | where {$_.PSIsContainer}
#FILES AND FOLDERS
$SourcePathFileOutput = Get-ChildItem $SourcePath -Recurse #| where {$_.PSIsContainer} #Uncomment for folders only
$HashOutput = ForEach ($file in $SourcePathFileOutput) {
Write-Output (New-Object -TypeName PSCustomObject -Property #{
Path = $file.FullName
IsDIR = $file.PSIsContainer
Directory = $File.DirectoryName
FileCount = (GCI $File.FullName -Recurse).Count
Parent = $file.Parent
Name = $File.Name
CreationTime = $File.CreationTime
LastAccessTime = $File.LastAccessTime
LastWriteTime = $File.LastWriteTime
Extension = $File.Extension
BaseName = $File.BaseName
B = $File.Length
#Root = $file.Root
#IsReadOnly = $file.IsReadOnly
#Attributes = $file.Attributes
#Owner = $acl.owner
#AccessToString = $acl.accesstostring
#Group = $acl.group
#MD5 = Get-FileHash $file.FullName -Algorithm MD5 | Select-Object -ExpandProperty Hash
#SHA1 = Get-FileHash $file.FullName -Algorithm SHA1 | Select-Object -ExpandProperty Hash
}) | Select-Object $CSVColumnOrder
}
$HashOutput | Export-Csv -NoTypeInformation -Path $DestinationCSVPath
I want to know how to add ID to each line in the csv file and also a parent ID to line in the csv.

try Something like this:
$ID=1
$SourcePath="c:\temp"
$SourcePathFileOutput=#()
#for have the parent dir
$SourcePathFileOutput += Get-Item $SourcePath | %{
$ParentPath=if ($_.PSIsContainer){$_.parent.FullName}else{$_.DirectoryName}
Add-Member -InputObject $_ -MemberType NoteProperty -Name "ID" -Value ($ID++)
Add-Member -InputObject $_ -MemberType NoteProperty -Name "PARENTPATH" -Value $ParentPath
$_
}
#for have all directory and file
$SourcePathFileOutput += Get-ChildItem $SourcePath -Recurse | %{
$ParentPath=if ($_.PSIsContainer){$_.parent.FullName}else{$_.DirectoryName}
Add-Member -InputObject $_ -MemberType NoteProperty -Name "ID" -Value ($ID++)
Add-Member -InputObject $_ -MemberType NoteProperty -Name "PARENTPATH" -Value $ParentPath
$_
}
#List dir for optimise
$DirOutput=$SourcePathFileOutput | where {$_.psiscontainer}
#for output result (add all properties you want)
$list=foreach ($Current in $SourcePathFileOutput)
{
$Result=[pscustomobject]#{
Path = $Current.FullName
PARENTPATH=$Current.PARENTPATH
ISDIR=$Current.psiscontainer
ID=$Current.ID
PARENTID=($DirOutput | where {$_.FullName -eq $Current.PARENTPATH}).ID
}
#Initialise parent root
if ($Result.PARENTID -eq $null) {$Result.PARENTID=0}
#send result on output
$Result
}
$list | Out-GridView

This should do what you want:
#Set-ExecutionPolicy Unrestricted
$SourcePath = "G:\My Drive"
$DestinationCSVPath = "e:\G Drive Inventory 20180611.csv" #Destination for Temp CSV File
$CSVColumnOrder = 'Path', 'IsDIR', 'Directory', 'FileCount', 'Parent', 'Name', 'CreationTime', 'LastAccessTime', 'LastWriteTime', 'Extension', 'BaseName', 'B','ID','ParentID'
#, 'Root', 'IsReadOnly', 'Attributes', 'Owner', 'AccessToString', 'Group' #, #'MD5', #'SHA1' #Order in which columns in CSV Output are ordered
#FOLDERS ONLY
#$SourcePathFileOutput = Get-ChildItem $SourcePath -Recurse | where {$_.PSIsContainer}
#FILES AND FOLDERS
$SourcePathFileOutput = Get-ChildItem $SourcePath -Recurse | Sort-Object Fullname #| where {$_.PSIsContainer} #Uncomment for folders only
$CurrentID = 1
$IDs = [ordered]#{}
$IDs.add(($SourcePathFileOutput[0].fullname | split-path),0)
$HashOutput = ForEach ($file in $SourcePathFileOutput) {
$IDs.add($file.fullname,$CurrentID)
Write-Output (New-Object -TypeName PSCustomObject -Property #{
ID = $CurrentID
ParentID = $IDs.$($file.fullname | split-path)
Path = $file.FullName
IsDIR = $file.PSIsContainer
Directory = $File.DirectoryName
FileCount = (GCI $File.FullName -Recurse).Count
Parent = $file.Parent
Name = $File.Name
CreationTime = $File.CreationTime
LastAccessTime = $File.LastAccessTime
LastWriteTime = $File.LastWriteTime
Extension = $File.Extension
BaseName = $File.BaseName
B = $File.Length
#Root = $file.Root
#IsReadOnly = $file.IsReadOnly
#Attributes = $file.Attributes
#Owner = $acl.owner
#AccessToString = $acl.accesstostring
#Group = $acl.group
#MD5 = Get-FileHash $file.FullName -Algorithm MD5 | Select-Object -ExpandProperty Hash
#SHA1 = Get-FileHash $file.FullName -Algorithm SHA1 | Select-Object -ExpandProperty Hash
}) | Select-Object $CSVColumnOrder
$CurrentID++
}
$HashOutput | Export-Csv -NoTypeInformation -Path $DestinationCSVPath
Explanation:
I piped $SourcePathFileOutput to Sort-Object because it is easiest to assign an ordered ID if things are sorted by their location in the directory tree.
$CurrentID starts at 1 because the first item in the loop is not the root parent. Your loop will increment this variable by 1 ($CurrentID++) at the end of each loop iteration so that the next file/directory will a new number. Since this code creates $CurrentID as an Int32 type, you will have issues if you have more than 2 billion files/directories. You will have to initialize it as a 64-bit type ($CurrentID = [long]1). However, I believe there can only be Int32 number of keys in a hash table, so a different strategy will need to be adopted if you have billions of files.
$IDs is a ordered hash table that tracks IDs for all files and directories. Each key in hash table is the path to the current item in the loop. The value is the ID assignment. This means you can access the ID using the syntax $IDs.path. After the initialization, I added the first entry with ID 0, which represents the root parent.
Inside of the loop, I created the ID property that just stores the current value of $CurrentID. I created 'ParentID', which looks up the parent directory inside of the $IDs hash table and returns that key's ID value.
I updated $CSVColumnOrder to have the ID and ParentID as columns.
You could have the ID scheme be slightly different if you do your initial sort differently. You don't have to increment by 1. You may have a requirement that you want directories to have smaller IDs than files and that will require more code (I did not see this requirement though).

Related

How to export csv of variables for each object loop

I have been stuck on trying to export in the format needed for this script for a month now. I can't figure out how to get it to export these variables in two separate loops into a single .csv file. We are given a .csv that contains staging_input and staging_location fields that both contain file locations on the network. We need to compare these two to make sure they are the same file count and size. I created a ForEach-Object loop for each of these fields and this gives me the desired output but I am unable to export-csv at the end of each loop into a single .csv.
Desired final output
Current output
#User input CSV File and Workorder
$workorder = Read-Host -Prompt 'Please enter the Fq job code'
$pos = $workorder.IndexOf("_")
$Client = $workorder.Substring(0, $pos)
$Matter = $workorder.Substring(6, $pos)
$job = $workorder.Substring($pos+7)
$csvoutputpath = "\\ldthost.pvt\client\" + $Client + "\" + $Matter + "\Proc\WKP\" + $job
$outputfilename = $workorder + ".csv"
$csvinputpath = Read-Host -Prompt 'Please Input the directory of the CSV file containing Staging input and Staging location'
$staginginput = Import-Csv $csvinputpath | select -ExpandProperty staging_input
$staginginputpath = $staginginput.TrimStart("\")
#Get Child Item for each line
$staginginputpath | ForEach-Object{
# In here, we do whatever want to the 'cell' that's currently in the pipeline
# Get File Counts
$staginginputcount = (Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$_ | Measure-Object).Count
#Get size
$staginginputsize = Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$_ | Measure-Object -property length -sum
$staginginputsize = $staginginputsize.sum / 1KB
}
$staginglocation = Import-Csv $csvinputpath | select -ExpandProperty staging_location
$staginglocationpath = $staginglocation.TrimStart("\")
#Get Child Item for each line
$staginglocationpath | ForEach-Object{
# In here, we do whatever want to the 'cell' that's currently in the pipeline
# Get File Counts
$staginglocationcount = (Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$_ | Measure-Object).Count
#Get size
$staginglocationsize = Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$_ | Measure-Object -property length -sum
$staginglocationsize = $staginglocationsize.sum / 1KB
}
##Export Final Output
$data = #()
$row = New-Object PSObject
$row | Add-Member -MemberType NoteProperty -Name "staging_input" -Value $staginginput
$row | Add-Member -MemberType NoteProperty -Name "staging_location" -Value $staginglocation
$row | Add-Member -MemberType NoteProperty -Name "staging_input_File_Count" -Value $staginginputcount
$row | Add-Member -MemberType NoteProperty -Name "staging_location_File_Count" -Value $staginglocationcount
$row | Add-Member -MemberType NoteProperty -Name "staging_input_File_Size" -Value $staginginputsize
$row | Add-Member -MemberType NoteProperty -Name "staging_location_File_Size" -Value $staginglocationsize
$data += $row
$Finaloutput = $csvoutputpath + "\" + $outputfilename
$data | Export-Csv $Finaloutput -NoTypeInformation -Append
Use a single loop instead of two:
#User input CSV File and Workorder
$workorder = Read-Host -Prompt 'Please enter the Fq job code'
$pos = $workorder.IndexOf("_")
$Client = $workorder.Substring(0, $pos)
$Matter = $workorder.Substring(6, $pos)
$job = $workorder.Substring($pos + 7)
$csvoutputpath = "\\ldthost.pvt\client\" + $Client + "\" + $Matter + "\Proc\WKP\" + $job
$outputfilename = $workorder + ".csv"
$csvinputpath = Read-Host -Prompt 'Please Input the directory of the CSV file containing Staging input and Staging location'
$Finaloutput = $csvoutputpath + "\" + $outputfilename
Import-Csv $csvinputpath |ForEach-Object {
# Calculate derived property values from `staging_input`
$staginginputpath = $_.staging_input.TrimStart("\")
$staginginputcount = (Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$staginginputpath | Measure-Object).Count
$staginginputsize = Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$staginginputpath | Measure-Object -property length -sum
$staginginputsize = $staginginputsize.sum / 1KB
# Calculate derived property values from `staging_location`
$staginglocationpath = $_.staging_location.TrimStart("\")
$staginglocationcount = (Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$staginglocationpath | Measure-Object).Count
$staginglocationsize = Get-ChildItem -Recurse -File -Force -LiteralPath \\?\UNC\$staginglocationpath | Measure-Object -property length -sum
$staginglocationsize = $staginglocationsize.sum / 1KB
# output new object with the property values calculated above
[pscustomobject]#{
staging_input = $_.staging_input
staging_location = $_.staging_location
staging_input_File_Count = $staginginputcount
staging_location_File_Count = $staginglocationcount
staging_input_File_Size = $staginginputsize
staging_location_File_Size = $staginglocationsize
}
} | Export-Csv $Finaloutput -NoTypeInformation

How can I get the time and date my PowerShell script deletes a file

I am using the following script to read a list of file names which are then deleted. Is there a way can get an output of the date and time each file is deleted?
$targetFolder = "D:\" $fileList = "C:\DeleteList.txt" Get-ChildItem
-Path "$targetFolder\*" -Recurse -Include #(Get-Content $fileList) | Remove-Item -Verbose
Thanks for any help.
You could keep track of the files that are deleted and the time of deletion by outputting an object with the file's fullname and current date.
This output can then be saved as structured CSV file
$targetFolder = "D:\"
$fileList = Get-Content -Path "C:\DeleteList.txt"
$deleted = Get-ChildItem -Path $targetFolder -Recurse -Include $fileList | ForEach-Object {
# output an object with the current date and the file FullName
$_ | Select-Object #{Name = 'DeletedOn'; Expression = {(Get-Date)}}, FullName
$_ | Remove-Item -WhatIf
}
# output on screen
$deleted | Format-Table -AutoSize
# output to csv file
$deleted | Export-Csv -Path 'C:\RemovedFiles.csv' -NoTypeInformation
Remove the -WhatIf safety-switch if you are satisfied with the results shown on screen.
Would this work?
$targetFolder = "D:"
$fileList = "C:\DeleteList.txt"
$Files = Get-ChildItem -Path "$targetFolder" -Recurse -Include #(Get-Content $fileList)
# Once you have the desires files stored in the $Files variable, then run a Foreach loop.
$Obj = #() # create an array called $Obj
Foreach ($File in $Files)
{
# store info in hash table
$hash = #{
DateTime = (get-date)
fileName = $File.name
fullpath = $File.fullname
}
Write-Host "deleting file $($file.name)" -for cyan
Remove-Item $File.fullname # *** BE VERY CAREFUL!!!***
# record information in an array called $Obj
$Obj += New-Object psobject -Property $hash
}
$Obj | select fileName, DateTime | Export-csv C:\...

Creating a Powershell script to get network folder information Problem with capturing and displaying LastWriteTime

Okay i am not a programmer and my Powershell experience is basic. But here goes. I have been asked to collect some info on a Directory we are migrating off our network.
It collects sub dirs names, size, #of files and folders and datestamp and exports to csv.
I cannot for the life of me make the folder creation date work so i gave up on that and have been looking to get the lastwritetime for the folders as i am trying to figure out what has been used recently. It only works for a few folders but the rest in excel have system.object[] in the cell. Super frustrating.
Here is the code. It uses a gui directory picker.
#Refresh network drives for session
net use i: /delete
net use m: /delete
net use i: "\\wfs.queensu.ca\ADV\Workgroups"
net use m: "\\wfs.queensu.ca\ADVMedia"
Function Get-Folder($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null
$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.Description = "Select a folder"
$foldername.rootfolder = "MyComputer"
if($foldername.ShowDialog() -eq "OK")
{
$folder += $foldername.SelectedPath
}
return $folder
}
$forDir = Get-Folder
#Change this to the parent directory that you want counts for
#$forDir = "\\wfs.queensu.ca\adv\workgroups\ADV Services\$seldir"
$Dirs = Get-ChildItem $forDir -Directory -Name
$Tab = [char]9
$results = #()
Write-Host $forDir
foreach($Dir in $Dirs)
{
$dirSize = "{0:N2} MB" -f ((Get-ChildItem $forDir/$Dir -Recurse | Measure-Object -Property Length
-Sum -ErrorAction Stop).Sum / 1MB)
$dirFiles = Get-ChildItem $forDir/$Dir -Recurse -File | Measure-Object | %{$_.Count}
$dirFolders = Get-ChildItem $forDir/$Dir -Recurse -Directory | Measure-Object | %{$_.Count}
#$dirDate = (Get-ChildItem $forDir/$Dir).LastWriteTime.ToString
$dirDate = #(Get-ChildItem $forDir/$Dir | % {$_.LastWriteTime})
$details = [ordered] #{
dir = $Dir
No_Files = $dirFiles
No_Folders = $dirFolders
size = $dirSize
date = $dirDate
}
$results += New-Object PSobject -Property $details
}
#This line finds the last index of the slash and adding one char
$Dirlength = $forDir.LastIndexOf('\') + 1
#This line takes the entire length of the string minus the postion above leaving the directory name
$sublength = $forDir.length - $Dirlength
#Assigns the remaining characters from the substring to the varibale to be used as the filename
$DirName = $forDir.SubString($Dirlength, $sublength)
$results | Export-Csv "C:\$DirName.csv" -NoTypeInformation
Write-Host ("Complete WOW!")
Get-ChildItem .\dir gives you all files contained in the directory .\dir not the directory itself.
That is why the following line in your script creates an array of LastWriteTimes for all files that are contained in the directory that $forDir/$Dir resolves to in your foreach loop:
$dirDate = #(Get-ChildItem $forDir/$Dir | % {$_.LastWriteTime})
The array in $dirDate will return ​System.Object[] when its toString() method is called. This is the reason, why you see this string in your excel, where you expect the folder's timestamp.
I bet that those folders, that seem to work do have exactly one childitem...
To get the LastWriteTime of the directory itself use Get-Item instead of Get-ChildItem.
$dirDate = Get-Item $forDir/$Dir | Select-Object -Expand LastWriteTime
try this...
Get-ChildItem -Path 'D:\temp' -Recurse |
Where-Object { $_.PSIsContainer } |
Select-Object -Property Name, LastWriteTime
<#
# Results
Name LastWriteTime
---- -------------
est 17-Feb-20 15:50:53
LogFiles 11-Mar-20 11:37:28
NewFolder 06-Feb-20 14:56:48
ParentFolder 12-Feb-20 14:24:25
Reference 03-Feb-20 11:55:47
Source 06-Feb-20 14:56:48
Target 24-Feb-20 22:03:56
New folder 03-Feb-20 11:55:24
temp 20-Jan-20 11:17:42
ChildFolder 12-Feb-20 14:08:11
GrandchildFolder 12-Feb-20 14:08:32
#>
# Or in v3 and beyond
Get-ChildItem -Path 'D:\temp' -Directory -Recurse |
Select-Object -Property Name, LastWriteTime
<#
# Results
Name LastWriteTime
---- -------------
est 17-Feb-20 15:50:53
LogFiles 11-Mar-20 11:37:28
NewFolder 06-Feb-20 14:56:48
ParentFolder 12-Feb-20 14:24:25
Reference 03-Feb-20 11:55:47
Source 06-Feb-20 14:56:48
Target 24-Feb-20 22:03:56
New folder 03-Feb-20 11:55:24
temp 20-Jan-20 11:17:42
ChildFolder 12-Feb-20 14:08:11
GrandchildFolder 12-Feb-20 14:08:32
#>
I know this question has already been answered, but for completeness, here's another way of doing this by utilizing the GetFileSystemInfos method every DirInfo object has.
$rootFolder = 'X:\YourRootPath'
Get-ChildItem -Path $rootFolder -Directory -Recurse | ForEach-Object {
# GetFileSystemInfos() (needs .NET 4+) is faster than Get-ChildItem and returns hidden objects by default
# See: https://devblogs.microsoft.com/powershell/why-is-get-childitem-so-slow/
$fsObjects = $_.GetFileSystemInfos('*', 'TopDirectoryOnly') # TopDirectoryOnly --> do not recurse
# you can also use Get-ChildItem here of course.
# To also get hidden files, with Get-ChildItem you need to add the -Force switch
# $fsObjects = Get-ChildItem -Path $_.FullName -Filter '*' -Force
# from the $fsObjects array, filter out the files and directories in order to get the count
$files = $fsObjects | Where-Object { $_ -is [System.IO.FileInfo] } # or: !($_.Attributes -band 'Directory')
$folders = $fsObjects | Where-Object { $_ -is [System.IO.DirectoryInfo] } # or: $_.Attributes -band 'Directory'
# emit a PSObject with all properties you wish to collect
[PsCustomObject]#{
Path = $_.FullName
FileCount = $files.Count
DirCount = $folders.Count
DirSize = "{0:N2} MB" -f (($files | Measure-Object -Sum -Property Length).Sum / 1MB)
DirDate = $_.LastWriteTime
}
} | Export-Csv -Path "X:\YourFolder_Info.csv" -NoTypeInformation -UseCulture

Child directory sizes and owners

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

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'
}