更快的方式:
好吧,我一直向自己承诺,我不会再把时间花在已解决的问题上了,但是...我的第二个答案中的switch语句在我的系统上运行需要10秒以上 - 因为它正在做“哪里”的东西在PowerShell而不是在LINQ中。
由于PowerShell不支持LINQ,我通过在Add-Type调用中编写静态辅助方法来解决它(并将该switch语句加速大约1000倍):
Add-Type -Language CSharpVersion3 -ReferencedAssemblies System.Xml, System.Xml.Linq -UsingNamespace System.Linq -Name XUtilities -Namespace Huddled -MemberDefinition @"
public static System.Collections.Generic.IEnumerable GetElementByIndex( System.Xml.Linq.XContainer doc, System.Xml.Linq.XName element, int index) {
return from e in doc.Descendants(element) where e.NodesBeforeSelf().Count() == index select e;
}
public static System.Collections.Generic.IEnumerable GetElementByValue( System.Xml.Linq.XContainer doc, System.Xml.Linq.XName element, string value) {
return from e in doc.Descendants(element) where e.Value == value select e;
}
"@
# Get the running processes to x(ht)ml
$xml = [System.Xml.Linq.XDocument]::Parse( "$(Get-Process | ConvertTo-Html)" )
# Find the index of the column you want to format:
$wsIndex = [Huddled.XUtilities]::GetElementByValue( $xml, "{http://www.w3.org/1999/xhtml}th", "WS" ) | %{ ($_.NodesBeforeSelf() | Measure).Count }
switch([Huddled.XUtilities]::GetElementByIndex( $xml, "{http://www.w3.org/1999/xhtml}td", $wsIndex )) {
{200MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: red;"); continue }
{20MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: orange;"); continue }
{10MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: yellow;"); continue }
}
# Save the html out to a file
$xml.Save("$pwd/procs2.html")
# Open the thing in your browser to see what we've wrought
ii .procs2.html
PowerShell 3:
在有人链接到这篇文章后,我在PowerShell 3中重新编写了这个,你不再需要编译类型来快速获取它:
Add-Type -AssemblyName System.Xml.Linq
$Process = $(Get-Process | Select Handles, NPM, PM, WS, VM, CPU, Id, ProcessName)
$xml = [System.Xml.Linq.XDocument]::Parse( "$($Process | ConvertTo-Html)" )
if($Namespace = $xml.Root.Attribute("xmlns").Value) {
$Namespace = "{{{0}}}" -f $Namespace
}
# Find the index of the column you want to format:
$wsIndex = [Array]::IndexOf( $xml.Descendants("${Namespace}th").Value, "WS")
foreach($row in $xml.Descendants("${Namespace}tr")){
switch(@($row.Descendants("${Namespace}td"))[$wsIndex]) {
{200MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: red;"); continue }
{20MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: orange;"); continue }
{10MB -lt $_.Value } { $_.SetAttributeValue( "style", "background: yellow;"); continue }
}
}
# Save the html out to a file
$xml.Save("$pwd/procs1.html")
# Open the thing in your browser to see what we've wrought
ii .procs2.html