31 filtered results
Normalizing whitespace:Get-ChildItem -Path C:\personal -Filter *.txt |
Select-Object Name, @{Name='Length'; Expression={'{0} KB' -f $_.Length/1KB}}
```
Aless0lyz2 2021-05-18: You need to double-up `{` and `}` inside an expandable string (`"..."`) - such as the one you're using to pass to the `-f` operator for string formatting - so that they aren't incorrectly interpreted by the parsing logic as being part of a subexpression (`$(...)`) embedded in the expandable string, which causes a syntax error:
```
# Enclose the format string in "..." so that the subexpression, $(...),
# is expanded, and double-up the { and } characters in the format string.
# Note: To get the size in KB, it is enough to divide by 1KB, which
# is more efficient than first dividing by 1024 and then reformatting.
Select-Object Name,
@{Name='Length'; Expression={"$('{0:N2} KB' -f ($_.Length / 1KB))"}}
```
Note: If you were using a single-quoted string, `'...'`, you wouldn't need to double the `{` and `}` characters - but then the subexpression wouldn't be expanded (string interpolation wouldn't happen).
As an aside: you could simply divide by `1KB` in order to get the size in KiB. If you need string formatting to control the formatting of the resulting number, you can use the `-as` operator:
```
# Use the -as operator to format the resulting number.
Select-Object Name,
@{Name='Length'; Expression={($_.Length / 1KB) -as 'N2'}}
```
If you do want to manually format the resulting number with a unit suffix, you could use script block (`{ ... }`) in lieu of a subexpression (`$(...)`) and use a `foreach` statement to advance to the result of the division:
```
# Use a script block ({ ... }) that implicitly outputs the result of
# the last statement, which is the output from the -f operator.
Select-Object Name,
@{Name='Length'; Expression={{'{0:N2} KB' -f ($_.Length / 1KB)}}}
```