I want to check how many pdf files a folder. For example in my C:\Temp\Test folder there are 6 pdf files and 6 txt files.
PS H:\> dir c:\temp\test
Directory: C:\temp\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 21/01/2022 10:05 PM 611 1.pdf
-a---- 26/01/2022 5:22 PM 0 1.txt
-a---- 22/01/2022 12:19 PM 3939 2.pdf
-a---- 26/01/2022 5:22 PM 0 2.txt
-a---- 08/01/2022 4:53 PM 27992 3.pdf
-a---- 26/01/2022 5:22 PM 0 3.txt
-a---- 08/01/2022 4:53 PM 27992 4.pdf
-a---- 26/01/2022 5:22 PM 0 4.txt
-a---- 22/01/2022 12:19 PM 3939 5.pdf
-a---- 26/01/2022 5:22 PM 0 5.txt
-a---- 21/01/2022 10:05 PM 611 6.pdf
If I use following PS, I got the right result 6
PS H:\> $directoryInfo = Get-ChildItem C:\Temp\Test | Where-Object {$_.Extension -eq ".pdf"}
$file_count = $directoryInfo.count
$file_count
6
However, when I use it like a function and deleted 2 pdfs in the folder. It still show as 6 pdfs. While, the $file_count in the function show as 4.
PS H:\> function CheckFileCount($Folder) {
$directoryInfo = Get-ChildItem $Folder | Where-Object {$_.Extension -eq ".pdf"}
$file_count = $directoryInfo.count
return $file_count
}
dir C:\Temp\Test
CheckFileCount C:\Temp\Test
Write-Host "There are $file_count PDFs in this folder."
Directory: C:\Temp\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 26/01/2022 5:22 PM 0 1.txt
-a---- 26/01/2022 5:22 PM 0 2.txt
-a---- 08/01/2022 4:53 PM 27992 3.pdf
-a---- 26/01/2022 5:22 PM 0 3.txt
-a---- 08/01/2022 4:53 PM 27992 4.pdf
-a---- 26/01/2022 5:22 PM 0 4.txt
-a---- 22/01/2022 12:19 PM 3939 5.pdf
-a---- 26/01/2022 5:22 PM 0 5.txt
-a---- 21/01/2022 10:05 PM 611 6.pdf
4
There are 6 PDFs in this folder.
It looks like the function can't return $file_count value. What's wrong here? Thank you in advance.
Thank you all and I think its been solved.
CodePudding user response:
Your function worked for me flawlessly when calling the function only.
I am adding a really good article about scopes in PowerShell: PowerShellScopes
Your problem is:
Write-Host "There are $file_count PDFs in this folder."
Try saving the function result to a var like so:
$function_result = CheckFileCount 'C:\Software\example'
And then view the result:
Write-Host "There are $function_result PDFs in this folder."
