I need to change a script which runs every 30 minutes. What it currently does, is checks for the presence of a file, and if it's currently in the location when the script runs, it will return the filepath for us to go an investigate why it hasn't been moved out yet.
We can't run this on the main import location because there are constantly files and it would result in an email every 30 minutes forever.
Can you please assist adding in a check for the date last modified on the item, so only those older than 30 minutes, when the check is run every 30 minutes, will be returned?
function folder_check {
param (
[Parameter(Mandatory=$true)] [string]$folder
)
if((Get-ChildItem -Attributes !Directory !System, !Directory !System Compressed $folder -force | Select-Object -First 1 | Measure-Object).Count -gt 0) {
Write-Host "Found"
return 1;
}
Write-Host "Not found"
return 0;
}
foreach ($folder in $folders) {
Write-Host "Checking $folder"
if (folder_check $folder) {
$found_folder = 1;
$lst = (gci -Attributes !Directory !System, !Directory !System Compressed -Path "$folder" -Force | Out-String -Width 80)
$body = ($body $lst);
}
}
CodePudding user response:
Get-ChildItem combined with switch -File
returns only files, not directories, so that replaces the need for attribute !Directory
.
You are using the cmdlet in combination with switch -Force
, and therefore it will also return items that otherwise can't be accessed by the user, such as hidden or system files. Leaving that parameter out, will take care of attribute !System
..
Also, I don't see the need for a function that iterates the files and returns an integer 1
or 0
to have the main script do almost exactly the same thing all over.
Remove the function folder_check
and adapt the code to be:
$refDate = (Get-Date).AddMinutes(-30)
$body = foreach ($folder in $folders) {
Write-Host "Checking $folder"
# gather a list of files older than 30 minutes ago
$lst = @(Get-ChildItem -Path $folder -File | Where-Object { $_.LastWriteTime -lt $refDate })
if ($lst.Count) {
# output the full path and filenames we have in array $lst
$lst.FullName
}
}
# now, $body will contain an array of full path and filenames to process further
$body
You didn't tell us what you wanted to do with that list later on, but from your comment I can see you want to send the found files in an email.
Then simply do:
if (@($body).Count) {
send_email
}