Reputation: 15
I am trying to use Get-Content and create a variable that will fill out a directory pathname based on each line of my file.
I have a long list of users in a .csv file and I want to check each of their usernames to get directory size.
The script works if I remove the $username variable and type the username manually at the end of $startdirectory.
$username = Get-Content 'C:\Scripts\AvayaUsers.csv'
$startDirectory = '\\xx\xxxx\xxxxxxxxxxx\users\$username'
$directoryItems = Get-ChildItem $startDirectory | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object
foreach ($i in $directoryItems)
{
$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 / 1GB) + " GB"
}
Upvotes: 0
Views: 671
Reputation: 8868
As others have pointed out, you are assigning all users to the end of the path, instead of each user one by one. You need another loop for each user. In addition to that there are a few other things that need attention.
$startDirectory = '\\xx\xxxx\xxxxxxxxxxx\users\$username'
Variables do not expand in single quotes, those should be double quotes.
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1GB) + " GB"
Seems you couldn't decide between concatenation or interpolation. Some will argue one way and vice versa. I recommend just picking one and staying consistent.
With these issues addressed you could end up with something like this.
$username = Get-Content 'C:\Scripts\AvayaUsers.csv'
foreach ($user in $username)
{
$startDirectory = "\\xx\xxxx\xxxxxxxxxxx\users\$user"
$directoryItems = Get-ChildItem $startDirectory -Directory | Sort-Object
foreach ($i in $directoryItems)
{
$subFolderItems = Get-ChildItem $i.FullName -File -Recurse -Force | Measure-Object -property Length -sum | Select-Object Sum
"{0} -- {1:N2}" -f $i.FullName,"$($subFolderItems.sum / 1GB) GB"
}
}
Also, if it is a CSV it may be preferable to treat it as such. If it's a single list you can still use it as CSV by specifying the header.
$username = Import-Csv -Path \path\to.csv -Header UserName
Upvotes: 1
Reputation: 255
You're telling the script to basically assign the entire $username as a variable and you don't loop through it.
This means the entire variable with all users is assigned to $startDirectory. I'm quite sure the script will work with only one user in the CSV.
You need to loop with a foreach each user included in the CSV and then get the file size as you sum.
Upvotes: 1