I need to find relative paths of folders and its files with length in MB in separate csv columns and compare that csv file with another csv file and print unmatched filepaths with length in another csv in absolute path
$srcpth = "C:\Users\vavenkatamanoj\Downloads"
$files = Get-ChildItem -Path $srcpth -File -Recurse
foreach ($f in $files)
{
$filen = $f.Name
$relativePath = $f.fullname.remove(0,($srcpth.length))
$filesize = $f.Length
Write-Output "$relativePath,$filesize" | Out-File C:\Users\vavenkatamanoj\Downloads\check.csv -Append
}
I try this script to get relative paths with size. It is ok but filepath and length are returned in the same column; I need separate columns. Can anyone help me?
CodePudding user response:
$srcpth = "C:\Users\vavenkatamanoj\Downloads"
$files = Get-ChildItem -Path $srcpth -File -Recurse
$result = foreach ($f in $files) {
[pscustomobject][ordered]@{
fileName = $f.Name
RelativePath = $f.fullname.remove(0,($srcpth.length))
FileSize = $f.Length
}
}
$result | Export-Csv "c:\temp\output.csv" -NoTypeInformation -Append
Use PSCustomObject for creating structured data. Please find the link below for more info: https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject?view=powershell-7.3
CodePudding user response:
Continuing from my comment,
Why not create a CSV file that has both the Length, the Absolute and the Relative path all in-one?
$srcpth = 'C:\Users\vavenkatamanoj\Downloads'
# needed for Resolve-Path -Relative
$currentPath = (Get-Location).Path
Set-Location $srcpth
# you could now remove the -Path $srcpth if you like
$result = Get-ChildItem -Path $srcpth -File -Recurse | ForEach-Object {
# output Objects
[PsCustomObject]@{
FileName = $_.Name
FileSize = $_.Length
RelativePath = $_.FullName | Resolve-Path -Relative
AbsolutePath = $_.FullName
}
}
# now, output the data as CSV
$result | Export-Csv -Path 'C:\Users\vavenkatamanoj\Downloads\check.csv' -NoTypeInformation
# restore the current location
Set-Location $currentPath