【发布时间】:2014-08-18 00:38:56
【问题描述】:
我编写了一个脚本来检查用户的桌面文件夹是否在 cuota 限制下,如果他们在 cuota 限制下,将正确地备份到服务器。
每个用户都有他的电脑,所以源 CSV 看起来像:
pc1,user1
pc2,user2
pc800,user800
一些计算机是 Windows Xp 和一些 W7,路径可能不同,因为我使用的是 Test-Path
W7 = C:\users\$user\desktop
XP = C:\document and settings\$user\desktop
但是 Test-Path 非常慢,我开始在每个 Test-path 之前使用 Test-Connection -count 1
无论如何,脚本仍然很慢,在每次“糟糕的 ping 测试”中我都会浪费很多时间。
代码:
$csvLocation = '~\desktop\soourceReport.csv'
$csv = import-csv $csvLocation -Header PCName, User
$OuputReport = '~\desktop\newReport.csv'
# info:
# "209715200" Bytes = 200 MB
$cuota = "209715200"
$cuotaTranslate = "$($cuota / 1MB) MB"
Write-Host "Cuota is set to $cuotaTranslate"
$count=1
foreach($item in $csv)
{
write-host "$count# Revisando" $item.User "en" $item.PCName "..." #For debug
if (Test-Connection -Quiet -count 1 -computer $($item.PCname)){
$w7path = "\\$($item.PCname)\c$\users\$($item.User)\desktop"
#echo $w7path #debug
$xpPath = "\\$($item.PCname)\c$\Documents and Settings\$($item.User)\Escritorio"
#echo $xp #debug
if(Test-Path $W7path){
$desktopSize = (Get-ChildItem -Recurse -force $w7path | Measure-Object -ErrorAction "SilentlyContinue" -property length -sum)
write-host -ForegroundColor Green "access succeed"
if($($desktopSize.sum) -gt $cuota){
$newLine = "{0},{1},{2}" -f $($item.PCname),$($item.User),"$("{0:N0}" -f $($desktopSize.sum / 1MB)) MB"
$newLine | add-content $outputReport
Write-Host -ForegroundColor Yellow "cuota exceeded! -- added"
}
else{
Write-Host -ForegroundColor DarkYellow "cuota OK"
}
}
elseif(Test-Path $xpPath){
$desktopSize = (Get-ChildItem -Recurse -force $xpPath | Measure-Object -ErrorAction "SilentlyContinue" -property length -sum)
write-host -ForegroundColor Green "access succeed"
if($($desktopSize.sum) -gt $cuota){
$newLine = "{0},{1},{2}" -f $($item.PCname),$($item.User),"$("{0:N0}" -f $($desktopSize.sum / 1MB)) MB"
$newLine | add-content $outputReport
Write-Host -ForegroundColor Yellow "cuota exceeded! -- added"
}
else{
Write-Host -ForegroundColor DarkYellow "cuota OK"
}
else{
write-host -ForegroundColor Red "Error! - bad path"
}
}
else{
write-host -ForegroundColor Red "Error! - no ping"
}
$count++
}
Write-Host -ForegroundColor green -BackgroundColor DarkGray "All done! new report stored in $report"
为了改进它,在第一次提到的 SLOW-Foreach 循环之前,我使用另一个 Foreach 将所有计算机存储在 $list 中。
foreach($pcs in $csv){
$alivelist += @( $pcs.PCName )
}
Test-Connection -quiet -count 2 -computer $alivelist
现在,我现在不知道如何在进入第二个 Foreach 之前从 SOURCE CSV 更新或删除行(“dead” pc、user)。
我需要你的一些“魔法”,或者至少是一些想法!
谢谢
【问题讨论】:
-
真正能加快速度的是并行处理。在 PS 2.0 中,您可以为此使用后台作业,而在 3.0 中则有工作流。在this question 中查看答案。
-
myitforum.com/cs2/blogs/gramsey/archive/2011/01/07/…。添加到@AlexanderObersht 关于后台作业的评论。我以前用过这个家伙的脚本
-
我在寻找快速 ping 清扫器时遇到了这个问题。我选择了这个脚本:gallery.technet.microsoft.com/scriptcenter/…
标签: powershell csv foreach