Search code examples
powershell-3.0

Can some one help in Powershell script to copy log files with last 24 hour time stamp


We have bunch of servers where we need to copy log files from multiple folders from each server and dump in a folder with respective server name, we need last 24 hours’ time stamp logs from these folders. We need to put this in schedule task.

And last 24 hours windows logs from event viewer from , Application Log, security log , system logs

Thank you for the help in advance.

Below is the code:

$ScriptStart = Get-Date
$PreviousTime = $ScriptStart.AddHours(-24)
$source = '\\Servername\Temp\test'
$destination = '\\Servername\Temp'
gci $source -Recurse -File | ? {
  $_.LastWriteTime -lt $ScriptStart -and
  $_.LastWriteTime -gt $PreviousTime
} | Copy-Item -Destination $destination
$temp = Get-EventLog -LogName Application -After $PreviousTime -Before $ScriptStart -ComputerName servername
$temp | select EventID, MachineName, message |
  Export-Csv '\\Servername\Temp\event1.csv'

I need this to be run on list of servers, with different folders. That is where I am stuck.


Solution

  • If I understand your question right, it should suffice if you changed your code to something like this:

    ...
    $servers = 'server_a', 'server_b', 'server_c', ...
    
    foreach ($server in $servers) {
      $source = "\\$server\Temp\test"
      $destination = "C:\central\folder\$server"
    
      if (-not (Test-Path -LiteralPath $destination)) {
        New-Item -Type Directory -Path $destination | Out-Null
      }
    
      Get-ChildItem $source -Recurse -File | Where-Object {
        $_.LastWriteTime -lt $ScriptStart -and
        $_.LastWriteTime -gt $PreviousTime
      } | Copy-Item -Destination $destination
    
      Get-EventLog -LogName Application -After $PreviousTime -Before $ScriptStart -Computer $server |
        Select-Object EventID, MachineName, Message |
        Export-Csv 'C:\path\to\events.csv' -Append -NoType
    }
    

    If the source folder differs per server, you may need to create a mapping of servername to source folder in a hashtable:

    $sourcePath = @{
      'server_a' = 'foo\bar'
      'server_b' = 'baz\something'
      ...
    }
    

    and change

    $source = "\\$server\Temp\test"
    

    to

    $source = '\\{0}\{1}' -f $server, $sourcPath[$server]