I would like to get size of user profiles across all servers in OU remotely, I tried this script, but without success
$Exclude = @('admsupp','all users','public','Default','Default user')
$servers = Get-ADComputer -SearchBase "OU=Horizon8,OU=xxx,OU=x,OU=xxx,DC=xx,DC=xx" -Filter *
foreach ($server in $servers)
{
gci -force -path \\$server.dnshostname\c$\users -Exclude $Exclude -ErrorAction SilentlyContinue | ? { $_ -is [io.directoryinfo] } | % {
$len = 0
gci -recurse -force $_.fullname -ErrorAction SilentlyContinue | % { $len = $_.length }
$_.fullname, '{0:N2} GB' -f ($len / 1Gb)
}
}
can someone advise please how to achieve this? Thank you
CodePudding user response:
The path you construct is wrong.
The way you write \\$server.dnshostname\c$\users will not give you what you think and you should either use a sub expression inside a double-quoted string:
Get-ChildItem -Path "\\$($server.DNSHostName)\c$\users"
or construct it using the -f Format operator like:
Get-ChildItem -Path ('\\{0}\c$\users' -f $server.DNSHostName)
Then, because you don't want to use recursion in the first Get-ChildItem, the -Exclude parameter does not function and instead use the -Directory switch and a Where-Object clause after that to exclude the folders you do not want:
Get-ChildItem -Path "\\$($server.DNSHostName)\c$\users" -Directory | Where-Object { $Exclude -notcontains $_.Name }
CodePudding user response:
Your problem is the way you construct the Path, see @Theo's answer.
But you can do it far more quickly with Measure-Object instead of another For-Each loop.
You don't have to test the DirectoryInfo type, unless you are still using PowerShell 2, simply use the -Directory parameter.
$Exclude = @('admsupp','all users','public','Default','Default user')
$servers = Get-ADComputer -SearchBase "OU=Horizon8,OU=xxx,OU=x,OU=xxx,DC=xx,DC=xx" `
-Filter *
foreach ($server in $servers)
{
gci -Force -Path "\\$($server.dnshostname)\c$\users" -Exclude $Exclude `
-Directory -ErrorAction SilentlyContinue |
% {
$_.Fullname, '{0:N2} GB' -f ((gci -Recurse -Force $_.Fullname `
-ErrorAction SilentlyContinue | Measure-Object `
-Property Length -Sum).Sum / 1Gb)
}
}
I Suggest you to prefer this
$_.Fullname, (gci -Recurse -Force $_.Fullname -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum).Sum
because reusing this info is easier than text data
