hello all,
while attempting to count files of a particular directory by running directly a command (shown below) my output is the expected one. However, when I’m wrapping that command into a function (or a variable) and then calling it from an if statement the output is not correct.
In specific, my Directory has 4 files at the moment.
[C:\Temp]> ls Directory: C:\Temp Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 16/07/2019 14:04 PM New folder d----- 16/07/2019 14:04 PM New folder - Copy -a---- 16/07/2019 14:04 PM 0 New Microsoft Word Document - Copy.docx -a---- 16/07/2019 14:04 PM 0 New Microsoft Word Document.docx
Creating a function to measure dir contents:
[C:\Temp]> function Get-DirContents { (([System.IO.Directory]::EnumerateFileSystemEntries("C:\Temp\")) | Measure-Object).Count }
Which seems to count dir contents
[C:\Temp]> Get-DirContents 4
and if I delete the files bring zero:
[C:\Temp]> Get-DirContents 0
when I’m adding that function to an if statement the result is not correct:
[C:\Temp]> if (Get-DirContents -eq '0') {Write-Host "dir is empty"} else {Write-Host "files copied"} dir is empty [C:\Temp]> Get-DirContents 4 [C:\Temp]> if (Get-DirContents -eq '0') {Write-Host "dir is empty"} else {Write-Host "files copied"} dir is empty
but this way works:
if ((([System.IO.Directory]::EnumerateFileSystemEntries("C:\Temp\")) | Measure-Object).Count -eq '0') {Write-Host "Dir is empty"} else { Write-Host "files copied"} files uploaded
I would like to understand why if I wrap the command into a function is not working and if use the command works.