我在这个网站上找到了一个有用的powershell脚本,它有一个计算文件/文件夹大小的功能。
我正在使用它,因为它对于大型文件/文件夹来说速度快且内存使用率低。
问题是当遇到一个文件夹时它无权访问我得到输出到控制台说拒绝访问。
Exception calling "GetFiles" with "0" argument(s): "Access to the path 'c:\users\administrator\AppData\Local\Applicati\
n Data' is denied."
At line:4 char:37
+ foreach ($f in $dir.GetFiles <<<< ())
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
我知道,或者认为我需要使用Out-Null来抑制错误,但仍然有脚本工作,但是我无法弄清楚在哪里或如何做到这一点,尽管多次尝试。
如果有人有任何想法,那么剧本如何?
function Get-HugeDirStats ($directory) {
function go($dir, $stats)
{
foreach ($f in $dir.GetFiles())
{
$stats.Count++
$stats.Size += $f.Length
}
foreach ($d in $dir.GetDirectories())
{
go $d $stats
}
}
$statistics = New-Object PsObject -Property @{Count = 0; Size = [long]0 }
go (new-object IO.DirectoryInfo $directory) $statistics
$statistics
}
$stats = Get-HugeDirStats c:\users
答案 0 :(得分:1)
您正在从DirectoryInfo对象中获取异常,因此您需要使用try / catch:
function Get-HugeDirStats ($directory) {
function go($dir, $stats)
{
try {
foreach ($f in $dir.GetFiles())
{
$stats.Count++
$stats.Size += $f.Length
}
foreach ($d in $dir.GetDirectories())
{
go $d $stats
}
}
catch [Exception] {
# Do something here if you need to
}
}
$statistics = New-Object PsObject -Property @{Count = 0; Size = [long]0 }
go (new-object IO.DirectoryInfo $directory) $statistics
$statistics
}
如果您从任何PowerShell cmdlet收到错误,可以在cmdlet上使用-ErrorAction SilentlyContinue
以防止错误打印到屏幕上。