Reputation: 33
I just would like some help removing the @{}
characters from my output
My script is to get the folder sizes from a specific Drive or Directory
Here is my script
$HugeFileSizeFolder= @() -join ','
$folder = "E:\New Folder\"
Get-ChildItem -Recurse $folder | Where-Object { $_.PSIsContainer } |
ForEach-Object {
$obj = New-Object PSObject
$Size = [Math]::Round((Get-ChildItem -Recurse $_.FullName | Measure-Object Length -Sum -ErrorAction SilentlyContinue).sum / 1000MB, 2)
$obj | Add-Member -MemberType NoteProperty -Name "Path" $_.FullName
$obj | Add-Member -MemberType NoteProperty -Name "SizeGB" $Size
if ($Size -ge 2)
{
$HugeFileSizeFolder +=$obj
}
}
$HugeFileSizeFolder | Out-string
$HugeFileSizeFolderFound = [boolean] $HugeFileSizeFolder
Here is a sample output
@{Path=E:\New Folder\Folder1; SizeGB=3.4GB}
I've tried the suggested tweaks but somehow I cannot get it to work ok maybe I'm not doing it right.
Your input and suggestions are very much appreciated
thanks Newbie
Upvotes: 1
Views: 938
Reputation: 439767
$HugeFileSizeFolder = @() -join ','
This makes $HugeFileSizeFolder
contain a string (the empty string), not an empty array, as is your intent - the array you're later trying to append to with +=
.
Because $HugeFileSizeFolder
is a string, +=
performs string concatenation, which results in representations such as @{Path=E:\New Folder\Folder1; SizeGB=3.4GB}
[1]
While $HugeFileSizeFolder = @()
would give you an empty array, it is better to avoid extending arrays iteratively with +=
, because doing so requires creating a new array behind the scenes in every iteration - see this answer.
The more efficient - and simpler - alternative is to use the pipeline as an assignment statement that automatically collects all outputs for you:
$folder = "E:\New Folder"
$HugeFileSizeFolder =
Get-ChildItem -Recurse $folder |
Where-Object { $_.PSIsContainer } |
ForEach-Object {
$obj = New-Object PSObject
$Size = [Math]::Round((Get-ChildItem -Recurse $_.FullName | Measure-Object Length -Sum -ErrorAction SilentlyContinue).sum / 1000MB, 2)
$obj | Add-Member -MemberType NoteProperty -Name "Path" $_.FullName
$obj | Add-Member -MemberType NoteProperty -Name "SizeGB" $Size
if ($Size -ge 2) {
# Output the object; all output objects are collected
# in $HugeFileSizeFolder
$obj
}
}
}
# Output the result (no need for Out-String)
$HugeFileSizeFolder
$HugeFileSizeFolderFound = [boolean] $HugeFileSizeFolder
As an aside: Since v3, PowerShell offers a fairly concise and efficient literal notation for creating [pscustomobject]
s, so your New-Object
and Add-Member
-based object construction could be simplified to:
$obj = [pscustomobject] @{
Path = $_.FullName
SizeGB = [Math]::Round((Get-ChildItem -Recurse $_.FullName | Measure-Object Length -Sum -ErrorAction SilentlyContinue).Sum / 1000MB, 2)
}
[1] A simple demonstration: '!' + [pscustomobject] @{ foo = 'bar' }
yields '!@{foo=bar}'
Upvotes: 1