Question

I am fairly new to PowerShell. I have created an exe that can be ran by a coworker that will go to 8 separate sql servers, to individual directories and check them for a list of created files. My current code checks for age less than one day and that it's not empty, however, I have been presented with a new problem. I need to be able to take a list in a text file/array/csv/etc and compare the list to the directory to ensure that there are not any additional files in the folder. All of the information is then formatted, exported to a file, and then emailed to certain recipients.

My question is, how do I create a script that works using this idea; preferably without considerable change to my current code as it is fairly length considering the sub directories of the 8 sql servers.. (current script redacted is as follows):

$today = get-date
$yesterday = $today.AddDays(-1)
$file_array = "XXX_backup*.trn", "XXX_backup*.bak", "XXY_backup*.trn", "XXY_backup*.bak"

$server_loc = \\hostname\e$\

$server_files = @(get-childitem $server_loc | where-object {$_.fullname -notmatch "(subdirectory)})

$server_complete_array = @("Files Directory ($server_loc)", " ")

foreach ($file in $files) {
    IF ($file.length -eq 0) {
        [string]$string = $file
        $server_complete_Array = $server_complete_Array + "$string is empty."
        }
elseif ($file.LastWriteTime -lt $yesterday) {
        [string]$string = $file
        $server_complete_Array = $server_complete_Array + "$string is old."
        }
else {
        [string]$string = $file
        $server_complete_Array = $server_complete_Array + "$string is okay."}
}

Thank you for your help in advance. :)

Was it helpful?

Solution

Bit of a hack, but it should work with what you already have:

$file_array = "XXX_backup*.trn", "XXX_backup*.bak", "XXY_backup*.trn", "XXY_backup*.bak"

$FileNames = $server_files | select -ExpandProperty Name
$FileCheck = ('$Filenames ' + ($file_array | foreach {"-notlike '$_'"}) -join ' ')

Since you're already using wildcards in your file specs, this works with that by creating a command which filters the file name array through a series of -notlike operators, one for each file spec.

$FileCheck

$Filenames -notlike 'XXX_backup*.trn' -notlike 'XXX_backup*.bak' -notlike 'XXY_backup*.trn' -notlike 'XXY_backup*.bak'

Each one will filter out the names that match the file spec and pass the rest onto the next -notlike operator. Whatever falls out the end didn't match any of them

At this point $FileCheck is just a string, and you'll need to use Invoke-Expression to run it.

$ExtraFiles = Invoke-Expression $FileCheck

and then $ExtraFiles should contain the names of all the files that did not match any of the file specs in $file_array. Since the filters are being created from $file_array, there's no other maintenance to do if you add or remove filespecs from the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top