当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 星期五有趣的颜色我的网站

作者:精品下载站 日期:2024-12-14 07:39:46 浏览:12 分类:玩电脑

星期五有趣的颜色我的网站


不久前,我发布了一篇文章,演示如何使用 Invoke-Webrequest,它是 PowerShell 3.0 的一部分。我使用 Manning.com 的页面来显示 Print 和 MEAP 畅销书。顺便说一下,感谢所有让 PowerShell 书籍继续流行的人。我原来的脚本只是将结果写到屏幕上。但我决定想要一种让我的书脱颖而出的方式,所以我做了一些小小的调整。


#requires -version 3.0

#this version will color code titles that contain the key word
#it must be run in the PowerShell console

Param(
[ValidateNotNullorEmpty()]
[string]$Keyword="PowerShell",
[ValidateScript({[enum]::GetNames([consolecolor]) -contains $_})]
[string]$Color="Green"
)

#the web address to retrieve
$url= "http://manning.com"

#this is a one-time request
$data = Invoke-Webrequest -Uri $url -DisableKeepAlive

<#
the print best sellers will be listed first
MEAP best sellers willbe second

$data.ParsedHtml.getElementsByTagName("div") | 
Where "classname" -eq "bestsellBox" | 
Select -First 1 -ExpandProperty InnerText

#>

#parse out the DIV tags looking for bestSellbox
$text = $data.ParsedHtml.getElementsByTagName("div") | 
Where "classname" -match "^bestsell" | 
Select -ExpandProperty InnerText 

foreach ($element in $text) {
  #parse the text
  $element.split("`n") | foreach {
    #write titles with keyword in the name in Green
    #won't work in the ISE
     if ($_.trim() -match $keyword ) { 
       $c = $color
      }
      else {
       #use the current console color
       $c = $host.ui.RawUI.ForegroundColor
      }
      #display the result
      Write-Host $_ -ForegroundColor $c
    }
  #insert a blank line between Print and MEAP bestsellers
  write "`r"
}

该脚本仍然使用 Invoke-Webrequest 解析来自 Manning.com 的页面。但我添加了一些逻辑来检查每个标题中的关键字,例如 PowerShell。如果找到,我定义一个颜色变量并使用 Write-Host 和该颜色显示结果。如果未找到,则颜色设置为当前前景色。该脚本只能在 PowerShell 控制台中运行。
现在,在有人开始大喊大叫使用 Write-Host 之前,是的,我意识到我所做的只是写入屏幕。但在这种情况下我对此很满意。我永远不需要做任何其他事情,感谢阅读信息并为其添加一些颜色使其变得更加容易。
不过,我确实通过添加参数来指定关键字和颜色来增加一些灵活性。我设置了一些默认值并包括参数验证。这是默认结果:

[玩转系统] 星期五有趣的颜色我的网站

但我可以轻松地检查其他值。

[玩转系统] 星期五有趣的颜色我的网站

显然,这个脚本实际上只对我或其他对我们的书的立场感到好奇的曼宁作者有用。但这是一篇周五有趣的文章,所以我希望您能学到有用的提示或技巧。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯