Powershell script that can log already scanned files and ignore them on next run?

前端 未结 3 863
[愿得一人]
[愿得一人] 2021-01-25 20:01

I am attempting to write a script that will recursively scan a directory, local files with the \'.Error\' extension, then email a group of people with a list of the files. I am

3条回答
  •  暖寄归人
    2021-01-25 20:38

    Try breaking the task into simple steps:

    • Read list of exclusions from file
    • Discover files
    • Filter files against list of exclusions
    • Send emails
    • Append new list of exclusions to file
    $exclusionFilePath = '.\path\to\exclusions\file.txt'
    if(-not(Test-Path $exclusionFilePath)){
        # Create the exclusion file if it doesn't already exist
        New-Item $exclusionFilePath -ItemType File
    }
    
    # read list of exclusions from file
    $exclusions = Get-Content -Path $exclusionFilePath
    
    # discover files
    $array = @((Get-ChildItem -Path \\SERVER\FOLDER -Recurse -Include *.Error).Fullname)
    
    # filter current files against list of exclusions
    $array = $array |Where-Object {$exclusions -notcontains $_}
    
    foreach($file in $array){
      # send emails
      sendEmail
    
      # append new file path to exclusions file
      $file |Add-Content -Path $exclusionFilePath
    }
    

    Bonus tip: parameterize your functions

    Relying on variables from the calling context is a bit of an anti-pattern, I'd strongly suggest refactoring your sendEmail function to something like:

    function Send-ErrorFileEmail {
        param(
            [string]$File
        )
        $MailMessageArgs = @{
            SMTPServer = "relay.EXAMPLE.com"
            From       = "Test@EXAMPLE.com" 
            To         = "user@EXAMPLE.com"
            Subject    = "Error loading XPOLL File - $file" 
            Body       = "This is the body" 
        }
        Send-MailMessage @MailMessageArgs
    }
    

    Then use it in the script like:

    Send-ErrorFileEmail -File $file
    

提交回复
热议问题