问题
I´m trying to make a Powershell script that reports if there´s a file older than x minutes on remote folder. I make this:
$strfolder = 'folder1 ..................'
$pocet = (Get-ChildItem \\server1\edi1\folder1\*.* ) | where-object {($_.LastWriteTime -lt (Get-Date).AddDays(-0).AddHours(-0).AddMinutes(-20))} | Measure-Object
if($pocet.count -eq 0){Write-Host $strfolder "OK" -foreground Green}
else {Write-Host $strfolder "ERROR" -foreground Red}
But there´s one huge problem. The folder is often unavailable for me bacause of the high load and I found out when there is no connection it doesn´t report an error but continues with zero in $pocet.count. It means it reports everything is ok when the folder is unavailable.
I was thinking about using if(Test-Path..) but what about it became unavailable just after passing Test-Path?
Does anyone has a solution please?
Thank you in advance
回答1:
I tried this line of your code and experienced the same result (no error even when the path doesn't exist) even with the default $ErrorActionPreference set to Continue.
$pocet = (Get-ChildItem \\server1\edi1\folder1\*.* ) | where-object {($_.LastWriteTime -lt (Get-Date).AddDays(-0).AddHours(-0).AddMinutes(-20))} | Measure-Object
Try this instead (removing the *.*
makes it error, but we can put that back in the -filter parameter):
$pocet = (Get-ChildItem \\server1\edi1\folder1 -Filter *.* ) | where-object {($_.LastWriteTime -lt (Get-Date).AddDays(-0).AddHours(-0).AddMinutes(-20))} | Measure-Object
However $pocet.Count will still equal 0 because you've essentially created an object of the type Microsoft.PowerShell.Commands.MeasureInfo
which exists in $pocet, and the count property is going to equal zero when nothing is passed to it.
Instead I'd try this:
try
{
$pocet = Get-ChildItem "\\server1\edi1\folder1" -Filter *.* -ErrorAction Stop | where-object { ($_.LastWriteTime -lt (Get-Date).AddMinutes(-20)) }
if(($pocet | Measure-Object).Count -eq 0)
{
Write-Output "Folder ok"
}
else
{
}
}
catch
{
Write-Output "Error getting items from folder"
Write-Output $Error[0].Exception.Message
}
来源:https://stackoverflow.com/questions/19862605/powershell-remote-folder-availability-while-counting-files