【问题标题】:Powershell script - gciPowershell 脚本 - gci
【发布时间】:2018-10-22 08:45:50
【问题描述】:

我正在尝试使用以下脚本将输出分成两个文件:

try {
    gci C:\Windows\System32 -r -Force | % {
        if (!$_.PsIsContainer) {
            $_.FullName;
            $file = $_.FullName
        }
    } > paths.txt
} catch [System.UnauthorizedAccessException] {
    $file > errors.txt
}

我知道您无法使用catch [System.UnauthorizedAccessException] 捕获非终止脚本,但我也不想将-ErrorAction Stopcatch [System.Management.Automation.ActionPreferenceStopException] 一起使用(例如here),因为我不会获取所有文件路径。

【问题讨论】:

  • 作为一个附带问题,尽量避免在脚本中使用别名(gci%),因为这会使它们更难维护。此外,如果您使用的是 PowerShell v3 或更高版本,则不需要使用$_.PsisContainer,但可以使用-Directory/-File 开关Get-ChilditemFileSystem Provider
  • @boxdog 感谢您的建议!

标签: windows powershell exception get-childitem unauthorizedaccessexcepti


【解决方案1】:

这对我有用

$epath2 = $null

Get-ChildItem -Path C:\Windows\System32 -Recurse -Force -Directory -ErrorVariable epath2 |
foreach {
     if ($?) {
       Out-File -InputObject $_.FullName -FilePath c:\test\paths.txt -Append
    } 
}

if ($epath2) {
  $epath2 | 
  foreach {
     ($_.Exception -split "'")[1] | Out-File -FilePath c:\test\errors.txt -Append
  }
}

在 -ErrorAction 变量中捕获错误并作为第二遍发送到 errors.txt。除了访问被拒绝之外,可能还有其他错误,但您会知道哪些文件夹出现了问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多