PowerShell Script for checking contents of log file in network share

56 views Asked by At

I'm trying to write a PS script to check a network folder which contains logfiles of erased systems, when the erase is run the output contains the system serial number, as part of the logfile name, so instead of scrolling or searching the network share manually I need a script that will check the network share for a series of serial numbers which I have in a CSV.

Currently I was trying this but it's failing:

$cred = Get-Credential
$sourceFolder = '\\domain\share\share\'
$data = Import-Csv -Path 'C:\folder\Serials.csv'
foreach ($item in $data) {

    $search = Get-ChildItem -Path $sourceFolder -Filter $item.Serial -File -Recurse -ErrorAction          SilentlyContinue | 
              Select-Object -First 1

    $item | Add-Member -MemberType NoteProperty -Name Present -Value (@($search).Count -gt 0)
}

$data | Export-Csv -Path 'C:\folder\results.csv' -NoTypeInformation

I've tried the script listed above and was hoping for the listed serials to show up with true beside them if they existed.

1

There are 1 answers

0
mklement0 On

Given that there's no conceptual problem with your code, based on your comment your issue may just be needing to be patient waiting for processing to finish:

  • Each Get-ChildItem -Filter ... -Recurse ... call inside your foreach loop can potentially take a long time to finish, if the target directory tree is large, especially on a network drive.

  • Since you're modifying all objects in your $data array up front, it can take a long time before the Export-Csv call is reached and file output is produced.

The following, PowerShell-idiomatic reformulation of your code uses a single pipeline with streaming output to the target CSV file, causing the output file to be filled one row at a time. For visual feedback, a simple Write-Host command is used to signal whenever a new output object gets emitted, by printing a single .:

$sourceFolder = '\\domain\share\share\'
Import-Csv C:\folder\Serials.csv |
  ForEach-Object {
    $present = [bool] (
      Get-ChildItem -Path $sourceFolder -Filter $_.Serial -File -Recurse -ErrorAction SilentlyContinue | 
      Select-Object -First 1
    )
    # Add the `.Present` property and output the modified object,
    # thanks to `-PassThru`
    $_ | Add-Member -PassThru Present $present
    # Simple, less performance-interfering substitute for a progress display:
    # Print a "." for every object emitted.
    Write-Host -NoNewline .
  } |
  Export-Csv C:\folder\results.csv -NoTypeInformation

Thus, even if the total runtime is large, you should see "wandering dots" in your terminal indicating progress, with each dot representing a new object being emitted / exported.