Home > front end >  Powershell: Using Test-Path in combination with OlderThan. Could someone please take a look and tell
Powershell: Using Test-Path in combination with OlderThan. Could someone please take a look and tell

Time:07-13

I create a file in a folder. Every 6 months the file needs updating. I would like the script to tell me if the file is:

  • less than 6 months old (in Green)
  • over 6 months old (yellow)
  • file does not exist (red)

The current output I am getting is either red (does not exist) or green (file is less than 6 months)

Even when the files is older than 6 months, it gives me the same output as green.

PSVersion 5.1.19041.1682

$playerID=$args[0]
$path = Test-Path O:\SPG\Gästedaten\*\*$playerID*\*KYC* -OlderThan(Get-Date).AddDays(-182)

if ($path -eq $false)
{
    Write-Host "This Guest has a VALID KYC. `n" -ForegroundColor Green
}
elseif ($path -eq $true)
{ 
    Write-Host "KYC is older than 6 months.`n" -ForegroundColor Yellow
}
else
{
    Write-Host "Guest has no file or folder.`n" -ForegroundColor Red
}

CodePudding user response:

There is a lot to do with your script. I don't love $arg[0] but I don't know enough about what you are doing to help with that.

Please look at the comments in the script below and above. Also please read https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7.2

https://stackoverflow.com/tour

$playerID = $args[0] 

#Check for the file and if not there stop everything.
$FileDate = $null
[date]$FileDate = Get-ChildItem -Path "O:\SPG\Gästedaten**$playerID**KYC*" -ErrorAction SilentlyContinue | Select-Object CreationTime
IF ($null -eq $FileDate) {
    Write-Host "Guest has no file or folder.`n" -ForegroundColor Red
    break
}

#Test the file for 6 months or older
If ($filedate -ge (Get-Date).AddDays(-182)) {
    Write-Host "KYC is older than 6 months.n" -ForegroundColor Yellow
}
Else {
    
    # everything else is good
    Write-Host "This Guest has a VALID KYC. n" -ForegroundColor Green 
}

If you want the time to simply be greater then 6 month change -ge to -gt


I knew the $arg[0] was wrong. If this isn't correct below I am sorry to say I am not understanding or don't know.

#Check for the files and if not there stop everything.
$files = @{}
$Files = Get-ChildItem -Path Get-ChildItem -Path O:\SPG\*KYCReport*.pdf | Select-Object CreationTime, Name
IF ($null -eq $Files) {
    Write-Host "Guest has no file or folder." -ForegroundColor Red
    break
}

#loop through the files
$files | ForEach-Object {
    #Test the file for 6 months or older
    If ( (Get-Date).AddDays(-182) -ge $_.CreationTime) {
        Write-Host "KYC $($_.name) is older than 6 months." -ForegroundColor Yellow
    }
    Else {
    
        # everything else is good
        Write-Host "This Guest has a VALID KYC." -ForegroundColor Green 
    }
}
  • Related