在foreach循环中添加一个超时,然后写入主机-Powershell



我有一个小脚本,它运行在csv文件中的所有共享路径中,并调用一个快速Get-ChildItem来计算文件夹/子文件夹中的文件数等。这很有效,但需要很长时间,尤其是当文件夹的文件数超过500k时。

我想在循环中添加一个超时,这样它只会写入主机,然后输出到另一列"超时",但我似乎无法使其工作。

我尝试了几种不同的方法,但不知何故,我的循环中断了,并一遍又一遍地运行csv中的顶部行。

这是我迄今为止的代码:


...
#Import middle to filter unique
$sharesMiddle = Import-Csv -Path './middle.csv' | Sort-Object NFTSPath -Unique
$result = foreach ($share in $sharesMiddle) {
#Replace the colon for $ within the path
$nftsPath = join-path \ $share.AssetName $share.Path.Replace(':', '$')
$path = $share.Path 
$count = Invoke-Command -computername $share.AssetName -ScriptBlock { param($path) (Get-ChildItem $path -File -Recurse).count } -Credential $Cred -Verbose -ArgumentList $path 
Write-Host $nftsPath : $count

$share | Select-Object *, @{n = "Files"; e = { $count } }

}
$result | Export-CSV '.newcsvfile.csv' -NoTypeInformation 

这方面的任何帮助都将是超级的!

谢谢。

我测试了以下应该适合您的内容:

# define the time limit in seconds
$TimeoutLimitSeconds = 2
# Define the job, start job
$job = Start-Job -ScriptBlock {420+69 ; start-sleep -Seconds 3}
# Await job
$job | Wait-Job -Timeout ( $TimeoutLimitSeconds ) | Out-Null
# If job doesn't finish before the time limit is reached
if ($job.state -eq 'Running') {
# Job timed out
$job | Stop-Job | Remove-Job
$job = $null
$output = "TIMED OUT"
# If job managed to finalize in time
}Else{
# Finished on time
$job | Stop-Job 
$output = Receive-Job $job
$job | Remove-Job
}
# Write the output to host
Write-Host "output is: $output"

输出为:超时

# define the time limit in seconds
$TimeoutLimitSeconds = 4
# Define the job, start job
$job = Start-Job -ScriptBlock {420+69 ; start-sleep -Seconds 3}
# Await job
$job | Wait-Job -Timeout ( $TimeoutLimitSeconds ) | Out-Null
# If job doesn't finish before the time limit is reached
if ($job.state -eq 'Running') {
# Job timed out
$job | Stop-Job | Remove-Job
$job = $null
$output = "TIMED OUT"
# If job managed to finalize in time
}Else{
# Finished on time
$job | Stop-Job 
$output = Receive-Job $job
$job | Remove-Job
}
# Write the output to host
Write-Host "output is: $output"

输出为:489

最新更新