I have a CSV file with user IDs and a script that already pulls the UNC path to the HomeDirectory, I'm hoping to query to pull the size of the user HomeDirectory and then add it to the CSV file. This is what I currently have:
$userlist = Import-Csv "C:\HomeShares\NToU.csv"
ForEach ($user in $userlist) {
$SamID_User = $user.NID
#A Search by SamAccountName
$result = Get-ADUser -Filter { samaccountname -eq $SamID_User } -Properties HomeDirectory |
Select-Object samaccountname,HomeDirectory
$result | Export-CSV "C:\HomeShares\new_names.csv" -NoTypeInformation -Append
}
Could someone please point me in the right direction on how to add in getting the folder size? I have researched the possibility of using RoboCopy to get this but I would need to use the new CSV file to do the source? Or is there an easier way in the existing ForEach loop?
CodePudding user response:
"{0} GB" -f [math]::Round(((Get-ChildItem -Path $sourcePath -Recurse -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB), 2)
where $sourcePath
is the path to ie. C:\users\jdoe\
CodePudding user response:
You could do something like this where you pull in the records from your csv, pipe them to ForEach-Object
, grab the matching account from AD using Get-ADUser
, use Get-ChildItem
to find all the files recursively in the user's home directory and finally use Measure-Object
to sum up the length/size.
Import-Csv 'C:\HomeShares\NToU.csv' |
ForEach-Object {
Get-ADUser -Filter "samaccountname -eq '$($_.NID)'" -Properties HomeDirectory |
ForEach-Object {
[PSCustomObject]@{
SamAccountName = $_.SamAccountName
HomeDirectory = $_.HomeDirectory
'HomeDirectorySize (GB)' = $(
'{0:f2}' -f ((Get-ChildItem $_.HomeDirectory -File -Recurse | Measure-Object Length -Sum).Sum / 1GB)
)
}
}
} | Export-Csv 'C:\HomeShares\new_names.csv' -NoTypeInformation -Append