Invoke-WebRequest 数据透视结果

问题描述 投票:0回答:1

我需要简单的脚本,该脚本将为 file.txt 中保存的每个站点执行 Invoke-WebRequest 命令,以显示文件中站点的 og:description。

到目前为止,我没有循环,但我可以使用下面的脚本获取 og:description

$response = Invoke-WebRequest https://www.w3schools.com/

[regex]$pattern = '"og:([^:]+?)" content="(.+?)"'

$pattern.Matches($response.Content).captures | ForEach-Object {
    ,$_.groups.value | ForEach-Object {
        [PSCustomObject]@{
            Name  = $_[1]
            Value = $_[2]
        }
    }
} | Where-Object { $_.Name -eq "description" -or $_.Name -eq "url" } | Export-Csv -Path "C:\Users\site_desc.csv" -NoTypeInformation

问题是结果没有像我所希望的那样保存,到目前为止我已经保存了

"Name","Value"
"description","FGH-5556"
"url","https://www.w3schools.com/"

我需要类似的东西,每个结果一行

"desciption","url"
"FGH-5556","https://www.w3schools.com/"
"....","...."
....

如何将结果转换为看起来更像 csv 而不是数组

感谢支持

powershell csv
1个回答
0
投票

建议执行以下操作的
PowerShell
脚本:

  1. 从“file.txt”读取网站列表
  2. 初始化一个数组来存储结果
  3. 循环访问每个网站,发送网络请求并提取 og:description 内容
  4. 处理无法访问网站的错误
  5. 将结果存储在自定义对象数组中
  6. 以表格形式显示结果

PowerShell
代码:

# Read the list of websites from file.txt
$websites = Get-Content -Path "file.txt"

# Create an array to store results
$results = @()

# Loop through each website
foreach ($site in $websites) {
    try {
        # Send web request and get content
        $response = Invoke-WebRequest -Uri $site -UseBasicParsing

        # Extract og:description using regex
        $description = if ($response.Content -match '<meta property="og:description" content="(.*?)"') {
            $matches[1]
        } else {
            "No og:description found"
        }

        # Add result to array
        $results += [PSCustomObject]@{
            Website = $site
            Description = $description
        }
    }
    catch {
        # Handle errors
        $results += [PSCustomObject]@{
            Website = $site
            Description = "Error: $($_.Exception.Message)"
        }
    }
}

# Display results in table format
$results | Format-Table -AutoSize
© www.soinside.com 2019 - 2024. All rights reserved.