我想检查多少个pdf文件的文件夹。例如,在我的C:\Temp\Test文件夹中,有6个pdf文件和6个txt文件。
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 如果我使用下面的PS,我得到了正确的结果
PS H:\> $directoryInfo = Get-ChildItem C:\Temp\Test | Where-Object {$_.Extension -eq ".pdf"}
$file_count = $directoryInfo.count
$file_count
6但是,当我像函数一样使用它并删除文件夹中的2个pdfs时。它仍然显示为6个pdfs。同时,函数中的$file_count显示为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.该函数似乎无法返回$file_count值。这里怎么了?提前谢谢你。
谢谢大家,我想这个问题已经解决了。
发布于 2022-01-26 07:22:36
当只调用函数时,您的功能为我完美地发挥了作用。
我在PowerShell:PowerShellScopes中添加了一篇关于作用域的非常好的文章
你的问题是:
写-主机“在这个文件夹中有$file_count PDF。
尝试将函数结果保存到一个var中,如下所示:
$function_result = CheckFileCount‘C:\Software\示例’
然后查看结果:
写-主机“在这个文件夹中有$function_result PDF。
https://stackoverflow.com/questions/70859374
复制相似问题