0

I'm trying to de-duplicate a ton of files spread across many folders using PowerShell. While logging progress in a transcript, I'm trying to include the number of files held in an array (representing the batch of files being checked), but the output is expanding the array into its contained values (file names) instead of the number of objects it contains.

Tried:

$files = "file1.txt","file2.txt","file3.txt","file4.txt"
Write-Output "`tNumber of files: $files.length"

And get:

     Number of files: file1.txt file2.txt file3.txt file4.txt

Then tried:

Write-Output "`tNumber of files: ",$files.length

and get:

     Number of files: 
4

Instead, I want:

     Number of files: 4

I thought writing to a transcript had something to do with it but broke it down into it's simplest part. What am I missing?

Since PS version might matter...

PS > $psversiontable

Name                           Value
----                           -----
PSVersion                      5.1.17763.3770
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.3770
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
MJA
  • 350
  • 1
  • 3
  • 15

1 Answers1

-1

Having read PowerShell difference between Write-Host and Write-Output? I found Write-Host gets me the desired output:

Write-Host "`tNumber of files: ",$files.length
>    Number of files: 4

I noticed some PowerShell messages not being captured in earlier trials and opted to use Write-Output instead of Write-Host but now see that was the wrong choice for my use case.

Per @abdulniyaspm, I was missing the subexpression operator $(…). Now I'm using:

Write-Host "`tNumber of files: $($files.length)"
>    Number of files: 4

Now I need to get more familiar with the various output streams.

MJA
  • 350
  • 1
  • 3
  • 15
  • 2
    Per @abdulniyaspm’s comment, your original issue was that Powershell was interpolating your string by replacing ```$files``` with the variable’s stringified value, whereas you wanted it to interpolate ```$files.length```. Inside a quoted string you need to wrap complex expressions in the “subexpression operator” - i.e. ```$(…)``` if you want the entire expression to be interpolated, rather than just the literal variable value. – mclayton Jun 23 '23 at 06:53