Powershell - 计算文件时的远程文件夹可用性 [英] Powershell - remote folder availability while counting files
问题描述
我正在尝试制作一个 Powershell 脚本,该脚本报告远程文件夹中是否存在超过 x 分钟的文件.我做这个:
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}
但是有一个大问题.由于高负载,该文件夹通常对我不可用,我发现当没有连接时,它不会报告错误,但在 $pocet.count 中继续为零.这意味着它在文件夹不可用时报告一切正常.
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.
我正在考虑使用 if(Test-Path..) 但它在通过 Test-Path 后变得不可用怎么办?
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?
先谢谢你
推荐答案
即使将默认的 $ErrorActionPreference 设置为 Continue,我也尝试了您的这一行代码并遇到了相同的结果(即使路径不存在也没有错误).
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
试试这个(删除 *.*
会使它出错,但我们可以把它放回 -filter 参数中):
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
然而,$pocet.Count 仍将等于 0,因为您实际上已经创建了一个类型为 Microsoft.PowerShell.Commands.MeasureInfo
的对象,该对象存在于 $pocet 中,并且 count 属性将当没有传递给它时等于零.
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.
相反,我会试试这个:
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
}
这篇关于Powershell - 计算文件时的远程文件夹可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!