我正在尝试编写一个脚本,它将从here获取财富100强URL,将这些URL放入一个数组中,然后编写一个运行空间,使用Invoke-WebRequest获取这些URL的内容,并将这些内容写入一个文件。这是我到目前为止所拥有的代码:
#Importing Modules
Import-Module PoshRSJob
#variable declaration
$page = Invoke-WebRequest https://www.zyxware.com/articles/4344/list-of-fortune-500-companies-and-their-websites
$links = $page.Links
$tables = @($page.ParsedHtml.GetElementsByTagName("TABLE"))
$tableRows = $tables[0].Rows
#loops through the table to get only the top 100 urls.
$urlArray = @()
foreach ($tablerow in $tablerows) {
$urlArray += New-Object PSObject -Property @{'URLName' = $tablerow.InnerHTML.Split('"')[1]}
#Write-Host ($tablerow.innerHTML).Split('"')[1]
$i++
if ($i -eq 101) {break}
}
#Number of Runspaces to use
#$RunspaceThreads = 1
#Declaring Variables
$ParamList = @($urlArray)
$webRequest = @()
$urlArray | start-rsjob -ScriptBlock {
#$webRequest = (Invoke-WebRequest $using:ParamList)
#Invoke-WebRequest $urlArray
#Invoke-WebRequest {$urlArray}
#Get-Content $urlArray
} 我现在遇到的问题是,我不能让Invoke-WebRequest或Get-Content给我数组中实际包含的URL的内容。您可以看到,在scriptblock中,我注释掉了一些不起作用的行。
我的问题是:使用运行空间,我需要做什么才能使用Get-Content从数组中的所有URL中提取数据,然后将其写入文件?
发布于 2018-04-28 17:41:45
您可以调整当前查询以获得前100个公司名称。这跳过了前面的空公司。考虑使用取代传统New-Object PSObject的[PSCustomObject] @{ URLName = $url }。
$urlArray = @()
$i = 0
foreach ($tablerow in $tablerows) {
$url = $tablerow.InnerHTML.Split('"')[1]
if ($url) {
# Only add an object when the url exists
$urlArray += [PSCustomObject] @{ URLName = $url }
$i++
if ($i -eq 100) {break}
}
}要并行运行请求,请使用带有脚本块的Start-RSJob。然后并行运行Invoke-Webrequest。请注意,在本例中,$_引用管道中的当前数组元素,该数组元素由一个具有URLName属性的对象组成,但您需要稍微小心在脚本块中使用的变量,因为它们可能不会按照您期望的方式进行解析。
# Run the webrequests in parallel
# $_ refers to a PSCustomObject with the @{ URLName = $url } property
$requests = ($urlArray | start-rsjob -ScriptBlock { Invoke-WebRequest -Uri $_.URLName })然后,您可以等待所有作业完成,并对结果进行一些后处理。这里只写网站内容的长度,因为页面本身很长。
# Get the results
# $_.Content.Length gets the length of the content to not spam the output with garbage
$result = Get-RSjob | Receive-RSJob | ForEach { $_.Content.Length }
Write-Host $resulthttps://stackoverflow.com/questions/50031556
复制相似问题