DIR命令遇无权限/锁定文件夹崩溃,求跳过方案或替代审计方法
解决SMB共享目录审计时DIR命令崩溃的问题
我之前也碰到过类似的困扰:DIR /s碰到无权限或锁定的文件夹直接中断,导致审计文件不完整。下面给你几个符合需求的解决方案,优先采用PowerShell实现(避免VBS),完美匹配你的要求:
方案一:PowerShell脚本(推荐)
这个脚本可以灵活指定要跳过的深层目录,处理权限错误不中断,还能输出和DIR完全一致的两种格式(带元数据/纯路径)。
1. 带元数据的输出(对应DIR /s)
保存为Audit-ShareWithMetadata.ps1:
# 定义需要跳过的文件夹路径(支持深层目录) $excludePaths = @( "appname\foo\nginx", "running-app\locked-dir", "another\path\to\skip" ) # 目标SMB共享目录(替换成你的共享路径,比如 "\\server\share") $targetShare = "\\your-server\your-share" # 遍历目录,跳过无权限项和指定排除路径 Get-ChildItem -Path $targetShare -Recurse -ErrorAction SilentlyContinue | Where-Object { # 检查当前项的路径是否包含需要排除的目录 $shouldExclude = $false foreach ($exclude in $excludePaths) { if ($_.FullName -like "*\$exclude\*" -or $_.FullName -eq Join-Path $targetShare $exclude) { $shouldExclude = $true break } } -not $shouldExclude } | ForEach-Object { # 模拟DIR命令的输出格式:文件大小(占19位)、修改时间(MM/DD/YYYY HH:MM AM/PM)、名称 if ($_.PSIsContainer) { # 文件夹的DIR输出格式 Write-Host ("{0,19} {1} <DIR> {2}" -f "", $_.LastWriteTime.ToString("MM/dd/yyyy hh:mm tt"), $_.Name) } else { # 文件的DIR输出格式 Write-Host ("{0,19:N0} {1} {2}" -f $_.Length, $_.LastWriteTime.ToString("MM/dd/yyyy hh:mm tt"), $_.Name) } } | Out-File -FilePath "audit-metadata.txt" -Encoding Default
2. 纯路径输出(对应DIR /s /b)
保存为Audit-ShareRawPaths.ps1:
$excludePaths = @( "appname\foo\nginx", "running-app\locked-dir" ) $targetShare = "\\your-server\your-share" Get-ChildItem -Path $targetShare -Recurse -ErrorAction SilentlyContinue | Where-Object { $shouldExclude = $false foreach ($exclude in $excludePaths) { if ($_.FullName -like "*\$exclude\*" -or $_.FullName -eq Join-Path $targetShare $exclude) { $shouldExclude = $true break } } -not $shouldExclude } | Select-Object -ExpandProperty FullName | Out-File -FilePath "audit-rawpaths.txt" -Encoding Default
脚本说明:
- 排除路径匹配:支持深层目录,比如
appname\foo\nginx会匹配所有该目录下的子项,以及目录本身 - 错误处理:
-ErrorAction SilentlyContinue会跳过无权限/锁定的文件夹,不会中断整个遍历 - 格式一致性:严格模拟
DIR的输出格式,包括文件大小的对齐、日期时间格式、文件夹标记<DIR>
方案二:CMD批处理(受限场景备用)
如果因为环境限制只能用CMD,这个批处理可以实现基本的路径排除,但处理权限错误的能力不如PowerShell(还是可能会有错误提示,但不会中断遍历):
@echo off set "targetShare=\\your-server\your-share" set "excludePaths=appname\foo\nginx running-app\locked-dir" set "outputFile=audit-rawpaths.txt" >%outputFile% ( for /r "%targetShare%" %%G in (*) do ( set "itemPath=%%~pG" setlocal enabledelayedexpansion set "skip=0" for %%E in (%excludePaths%) do ( if "!itemPath!"=="\%%E\" set "skip=1" ) if !skip! equ 0 echo %%G endlocal ) )
注意:这个批处理只能排除特定的文件夹路径,无法处理权限错误导致的中断,仅作为PowerShell方案的备用选项。
使用步骤:
- 替换脚本中的
$targetShare为你的SMB共享路径 - 修改
$excludePaths为需要跳过的文件夹列表 - 运行PowerShell脚本(需要确保有PowerShell执行权限,若受限可执行
Set-ExecutionPolicy RemoteSigned临时调整)
内容的提问来源于stack exchange,提问作者Plume
相关产品推荐
相关产品推荐

