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

[玩转系统] 抓取系统内部

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

抓取系统内部


[玩转系统] 抓取系统内部

我知道我可以通过几个不同的命令轻松地从 http://live.sysinternals.com 获取 html 内容。为了简单起见,我选择使用 Invoke-RestMethod。

[string]$html = Invoke-RestMethod "http://live.sysinternals.com"

因为 $html 是一个具有可预测模式的长字符串,所以我意识到我可以使用脚本将文本转换为使用命名正则表达式模式的对象。在我的测试脚本中,我引用了该脚本。

#need this function
. C:\scripts\convertfrom-text.ps1

现在是有趣的部分。我必须构建一个正则表达式模式。最终我得到了这个:

$pattern = "(?<date>\w+,\s\w+\s\d{1,2},\s\d{4}\s+\d{1,2}:\d{2}\s+\w{2})\s+(?<size>\d+)\s+<A HREF=""/(?<name>\w+(\.\w+){1,2})"

如果您使用过 Sysinternals 站点,您会知道还有一个 Tools“子文件夹”,它看起来与顶级站点基本相同。我的模式适用于顶级网站。有了这种模式,为每个工具创建对象数组并不困难。

$data = $html | ConvertFrom-Text $pattern | 
Select @{Name="LastModified";Expression={$_.Date -as [DateTime]}},
@{Name="Size";Expression={$_.Size -as [int]}},Name,
@{Name="Path";Expression={ "http://live.sysinternals.com/$($_.name)"}}

[玩转系统] 抓取系统内部

接下来,我检查本地目录并获取最新的文件。

#get most recently modified local file
$localfiles = dir G:\Sysinternals
$lastLocal = ( $localfiles | sort LastWriteTime | select -last 1).LastWriteTime

然后我可以测试本地不存在或网站上较新的文件。

#find files that have a newer time stamp or files that exist remotely but not locally
$needed = $data | where { ($_.LastModified -gt $lastlocal) -OR ( $localfiles.name -notcontains $_.name ) }

如果有需要的文件,那么我创建一个 System.Net.WebClient 对象并下载文件。

if ($needed) {
    Write-Host "Getting $($needed.count) updated files" -ForegroundColor Cyan
    $needed | foreach -begin { $wc = New-Object System.Net.WebClient 
    } -process {
     $target = Join-Path -Path "G:\Sysinternals" -ChildPath $_.name
     $source = $_.Path
     Write-host "Updating $target from $source" -ForegroundColor Green
     $wc.DownloadFile($source,$target)
    }
}
else {
    Write-Host "No updated files detected" -ForegroundColor Cyan
}

最终结果是我可以非常快速地更新本地 Sysinternals 文件夹,而不必担心使用 Webclient 服务的计时问题。

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

取消回复欢迎 发表评论:

关灯