In my testing, the PhysicalPath
property can contain cmd.exe formatted variable %SystemDrive%
.
When this occurs, you can take the physical path and extract the environment variable name and the remaining path using regex. Pull out the value of the variable and build the path.
$filepath = 'C:\sites.csv'
$sites = get-website
foreach($site in $sites) {
if($site.physicalPath -match '^%(.+)%(.+)$'){
$sitedir = Join-Path (Get-Content "env:$($matches.1)") $matches.2
Get-ChildItem -LiteralPath $sitedir
}
}
If you confirm this does accurately list the files for each site, it seems you've figured out the measurement portion.
A couple of other suggestions. First, I recommend Export-Csv
instead of Out-File
.
Next, instead of opening the file and appending over and over (slow) you can collect all the results and then write them.
$results = foreach($site in $sitelist){
... code ...
}
$results | Out-File $filepath
Or you can use ForEach-Object
and take advantage of the pipeline.
$sitelist | ForEach-Object {
... code ...
} | Out-File $filepath
A side benefit of ForEach-Object
is the -OutVariable
parameter which lets you capture the output in a variable (that is of type ArrayList
) and see the output (or pipe it on to more commands.)
Considering my recommendations, I'd give this a shot.
$filepath = 'C:\sites.csv'
$sites = get-website
$sites | ForEach-Object {
$ip, $port, $hostHeader = $_.bindings.collection.bindinginformation.split(":")
$path = if($_.physicalPath -match '^%(.+)%(.+)$'){
Join-Path (Get-Content "env:$($matches.1)") $matches.2
}
else{
$_.physicalpath
}
$size = (Get-ChildItem $path -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB
[PSCustomObject]@{
Name = $_.name
FullPath = $path
IP = $ip
Port = $port
HostHeader = $hostHeader
SizeMB = $size
}
} -OutVariable results
$results | Export-Csv $filepath -NoTypeInformation