我有一个PowerShell脚本,可以从服务器中获取配置文件,解析一些数据,然后ping设备以查看它们是在线还是离线。它按预期工作100% - 但运行时间超过8小时。我只是想知道我的逻辑中是否存在导致这种情况发生的事情。我确实意识到它可能与其他问题有关,但我想排除这一点。任何人都可以看到导致它花费更长时间的逻辑错误,即它是否会陷入某种循环中等等?
这是我的代码:
$logfile = "D:\Logs\MPOSPrinterPingLog.txt"
$offlineprinters = "D:\Reports\MPOS\MPOSOfflinePrinters.txt"
if (Test-Path $logfile) {Remove-Item $logfile}
if (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
Add-Content $logfile "Setting local path"
$localPath = "C:\Temp\MPOS"
Add-Content $logfile "Gathering server list"
$serverList = (Get-ADComputer -Filter "Name -like 'Q0*P30' -or Name -like 'Q0*P32'" -SearchBase "OU=Print,OU=Prod,OU=POS,DC=COMPANY,DC=NET").name | Sort-Object | Out-File C:\Temp\MPOS\MPOSPrintServers.txt
$serverListPath = "C:\Temp\MPOS\MPOSPrintServers.txt"
#Retrieve a list of MPOS Print servers from text file and set to $serverNames
Add-Content $logfile "Compiling text file"
$serverNames = Get-Content -Path $serverListPath
#Iterate through each of the server names
foreach ($serverName in $serverNames) {
Add-Content $logfile "Processing $serverName"
#Check if the server is online before doing the remote command
if (Test-Connection -ComputerName $serverName -Quiet -count 1) {
Add-Content $logfile "$serverName is online"
#copy config file from MPOS print to local server for processing
$timestamp1 = (Get-Date -Format g)
Add-Content $logfile "$timestamp1 - Copying xml file from server to local path"
$configPath = "\\$($serverName)\C$\ProgramData\Microsoft\Point Of Service\Configuration\Configuration.xml"
Copy-Item $configPath $localPath
#process xml file to parse IP addresses for ping
$timestamp2 = (Get-Date -Format g)
Add-Content $logfile "$timestamp2 - Processing xml file from $serverName to parse data to csv"
$xml = [xml](Get-Content C:\Temp\MPOS\Configuration.xml)
$PrinterNames = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property @{LogicalName=$_.LogicalName.Name}}
$PrinterIPs = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property @{HardwarePath=$_.HardwarePath}}
foreach ($PrinterIP in $PrinterIPs) {
$pingableIP = $PrinterIP.HardwarePath
if (Test-Connection $pingableIP -Quiet -Count 1) {
$timestamp3 = (Get-Date -Format g)
Add-Content $logfile "$timestamp3 - $serverName, $pingableIP is online and pingable"
} else {
$timestamp3 = (Get-Date -Format g)
Add-Content $offlineprinters "$timestamp3 - $serverName, $pingableIP is offline!"
}
}
} else {
Add-Content $logfile "$serverName is offline!"
}
}
答案 0 :(得分:3)
所以我相信你因为ping而面临问题,我不认为AD查询占用了大部分时间,所以你应该做的 - 与ping是平行的。 PoshRSJob将是开始的好地方。
foreach ($serverName in $serverNames) {
start-rsjob -Name $_ -ScriptBlock {
# your code in the loop goes here #
}
}
Get-RSjob | Receive-RSJob
或者您可以编写自己的运行空间包装器;) 如果你感兴趣的话,我有一个解析文本文件的脚本,它需要6-7分钟才能完成,在我将运行空间实现为并行的东西后,它开始在5毫秒内完成。这有多疯狂?的xD