Powershell - remote folder availability while counting files

二次信任 提交于 2019-12-25 05:23:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!