如何自动从多台远程计算机收集文件大小数据?

问题描述 投票:0回答:1

我正在致力于自动收集来自

的文件大小(
EXAMPLE.ENG

D:\Dump\logs\default\Rk7\base\

跨同一子网上的 140 多台计算机,并将结果(包括 IP 地址)写入 Excel 电子表格。这些机器可以通过 TeamViewer/VPN 访问,我正在尝试使用 PowerShell 来实现这一点。

我编写了以下最小版本的脚本来收集文件大小数据,但它没有按预期工作。它要么写入标头

Computer,FileSize(Bytes)
而没有实际文件大小,要么抛出错误指示找不到文件。如果我能在哪里出错,我将不胜感激。

这是脚本:

$targetIP = "10.168.0.45"
$remotePath = "D:\Dump\logs\default\Rk7\base\EXAMPLE.ENG"
$resultPath = "C:\result.csv"

if (-not (Test-Path $resultPath)) {
    "Computer,FileSize(Bytes)" | Out-File -FilePath $resultPath -Encoding utf8
}

$credential = Get-Credential -Message "Enter credentials for remote access to $targetIP"

if ($null -eq $credential) {
    Write-Host "Error: Credential is null. Please provide valid credentials."
    exit
}

try {
    $session = New-PSSession -ComputerName $targetIP -Credential $credential -ErrorAction Stop
    
    $result = Invoke-Command -Session $session -ScriptBlock {
        param($path)
        if (Test-Path $path) {
            $fileInfo = Get-Item $path -ErrorAction Stop
            return $fileInfo.Length
        } else {
            throw "File not found at the specified path: $path"
        }
    } -ArgumentList $remotePath
    
    "$targetIP,$result" | Out-File -FilePath $resultPath -Append -Encoding utf8
    Write-Host "Processed $targetIP: File size is $result bytes" -ForegroundColor Green
}
catch {
    $errorMessage = "Error processing ${targetIP}: $($_.Exception.Message)"
    Write-Host $errorMessage -ForegroundColor Red
    "$targetIP,Error: $($_.Exception.Message)" | Out-File -FilePath $resultPath -Append -Encoding utf8
}
finally {
    Remove-PSSession -Session $session -ErrorAction SilentlyContinue
}

Write-Host "Process completed. Results saved to $resultPath"

具体问题:

  • 脚本运行但未收集或写入正确的文件大小。

  • 错误如:

    Error processing 10.168.0.45: File not found at the specified path: \\10.168.0.45\D$\D:\Dump\logs\files\EXAMPLE.ENG

  • 有时,仅将标题

    Computer,FileSize(Bytes)
    写入文件,而没有实际数据。

环境:

  • 可通过 VPN 或 TeamViewer 访问机器。

  • 使用 PowerShell 5.1 在 Windows 11 上运行。

问题:

  1. 我应该继续调试此 PowerShell 脚本,还是我遗漏了一些可以简化流程的明显内容?

  2. 有人可以帮我解决文件访问问题并确保收集正确的文件大小吗?

windows powershell automation collect
1个回答
1
投票

既然你说所有机器都在同一个子网上,我将通过使用 UNC 路径直接读取文件长度来获取信息,例如

\\10.168.0.45\D$\Dump\logs\files\EXAMPLE.ENG

尝试

$targetIP   = '10.168.0.45', '10.168.0.30', '10.168.0.47'        # etc. array of computernames or IP addresses
$remotePath = '\\{0}\D$\Dump\logs\default\Rk7\base\EXAMPLE.ENG'  # template path where the computer's name of IP gets filled in
$resultPath = 'C:\result.csv'                                    # path for the resulting csv file on YOUR machine
$credential = Get-Credential -Message "Enter credentials for remote access to $targetIP"

# loop over the computers in the $targetIP array and collect the wanted info
$result = foreach ($computer in $targetIP) {
    if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {   # if needed add  -Credential $credential
        # create the path to the file. i.e. \\10.168.0.45\D$\Dump\logs\default\Rk7\base\EXAMPLE.ENG
        $filePath = $remotePath -f $computer
        $fileInfo = Get-Item -LiteralPath $filePath -ErrorAction SilentlyContinue # if needed add  -Credential $credential
        if ($fileInfo) {
            # output an object with the wanted properties to be collected in variable $result
            [PsCustomObject]@{
                'Computer'        = $computer
                'FileSize(Bytes)' = $fileInfo.Length
            }
        }
        else {
            Write-Warning "File $filePath not found.."
        }
    }
    else {
        Write-Warning "Computer $computer is not reachable.."
    }
}

# finally, write the $results to a CSV file
$result | Export-Csv -Path $resultPath -UseCulture -NoTypeInformation -Encoding UTF8
© www.soinside.com 2019 - 2024. All rights reserved.