1

我一直在尝试运行此脚本,该脚本捕获共享目录中的所有文件/文件夹并将其传递回 splunk。然而,即使我能找到的最长路径有 197 个字符,脚本也会给出 PathTooLongException 。

我尝试将共享映射为 C 驱动器根目录上名为 z 的文件夹,但这根本没有帮助。有人可以阐明如何解决这个问题或导致错误的原因吗?

param (
[string]$directory = "C:\Windows\Logs"
 )
 $errorCount = 0
$OutputList = @()
$directoryLink = 'c:\z'

#set up symbolic link
cmd /c mklink /d $directoryLink $directory

 try
{
$colItems = (Get-ChildItem -Path $directoryLink -Recurse | Sort-Object) 
}
catch
{
$errorCount += 1   
}
foreach ($i in $colItems) 
{
try
{        
    $subFolderItems = (Get-Item $i.FullName | Measure-Object -property 
    length -sum -ErrorAction SilentlyContinue) 
    $acl=$i.GetAccessControl()
    $SizeValue= [Math]::Round(($subFolderItems.sum / 1MB),3)

    $SplunkFileList = New-Object PSObject  
    $SplunkFileList | Add-Member -type NoteProperty -name Filename -Value $i.FullName
    $SplunkFileList | Add-Member -type NoteProperty -name SizeMb -Value $SizeValue
    $SplunkFileList | Add-Member -type NoteProperty -name LastAccess -Value $i.LastAccessTime
    $SplunkFileList | Add-Member -type NoteProperty -name Owner -Value $acl.Owner

    if ($i.PSIsContainer)
    {
        $SplunkFileList | Add-Member -type NoteProperty -name Type -Value "D"
    }
    else
    {
        $SplunkFileList | Add-Member -type NoteProperty -name Type -Value "F"
    }

    $OutputList += $SplunkFileList  

} 
catch [System.IO.IOExeception]
{
    Write-Host 'An Exception was caught.'
    Write-Host "Exception : $($_.Exception.GetType().FullName)"
    $errorCount += 1
    }   
} 
$OutputList | Select-Object Filename,SizeMb,LastAccess,Owner,Type | Format-
List
4

1 回答 1

3

如果您使用的是现代版本的 Powershell(我认为是 v5.1+),则可以使用 Windows API 的 unicode 版本获得超过 260 个字符的路径。

为此,您可以在路径前加上\\?\例如:

Get-ChildItem -LiteralPath '\\?\C:\Windows\Logs' -Recurse

注意:LiteralPath代替Path


如果要使用 UNC 路径 ( \\server\C$\folder),则语法略有不同:

Get-ChildItem -LiteralPath '\\?\UNC\server\C$\folder' -Recurse 
于 2018-09-20T09:18:07.550 回答