繁体   English   中英

使用 PowerShell 为 CSV 中的每一行添加内容

[英]Add-Content for each line in a CSV using PowerShell

我正在创建一个简单的脚本来从用户的文件路径中提取 chrome 扩展名,在 chrome 应用商店中搜索扩展名,然后将其输入到 csv 中:

# Open file
$file = Import-Csv 'filepath'

# Loop through each line of CSV
foreach ($line in $file)
{       
    # Assign file path, and regex just the extension
    $path = $line.path
    $extension = $path -replace '.*\\Extensions\\'

    # Open chrome webstore for specific extension
    $result = Invoke-webrequest -Uri "https://chrome.google.com/webstore/detail/$extension" -Method Get
    $resultTable = @{}  
    
    # Grab title of extension and place in CSV
    $title = $result.ParsedHtml.title
    Add-Content -Path 'filepath' -Value "$path,$extension,$title"
    
    # Create table and return as an object
    $resultTable.$extension = $title
    Write-Output $resultTable
}

这样做工作正常,但将结果附加到表的底部而不是在它的相邻列中,如下所示: 在此处输入图片说明

我将如何简单地将输出放入旁边的字段中,而不是添加到底部?

任何帮助将不胜感激,并提前感谢您。

编辑:让事情更清楚一点。 该文件最初如下所示:

在此处输入图片说明

我想要的输出是将扩展名和标题放在同一行,但相邻的列中,例如:

在此处输入图片说明

由于您使用Import-Csv来读取您的文件,我认为它是一个正确的 CSV,您可以使用Export-Csv输出自定义对象。

# Open file
$file = Import-Csv 'filepath'

# Loop through each line of CSV
# store results in $resultTable
$resultTable = foreach ($line in $file)
{       
    # Assign file path, and regex just the extension
    $path = $line.path
    $extension = $path -replace '.*\\Extensions\\'

    # Open chrome webstore for specific extension
    $result = Invoke-WebRequest -Uri "https://chrome.google.com/webstore/detail/$extension" -Method Get
    
    # Grab title of extension and place in CSV
    $title = $result.ParsedHtml.title
    
    # Create and output custom object with path,extension,title properties
    [pscustomobject]@{
        Path = $path
        Extension = $extension
        Title = $title
    }
}
# Export to CSV overwriting 'filepath'
$resultTable | Export-Csv 'filepath' -NoType

Export-Csv CSV 将输入对象转换为 CSV。 对象的每个属性成为一列,每个属性值都在这些相应的列下输出。 在对象数组的情况下,每个对象都成为自己的行。

您可以使用[PSCustomObject]构造每一行,然后使用Export-Csv导出,而不是直接写入文件

Import-Csv 'filepath' | ForEach-Object {
    $extension = $_.path -replace '.*\\Extensions\\'
    $result = Invoke-webrequest -Uri "https://chrome.google.com/webstore/detail/$extension" -Method Get
    $title = $result.ParsedHtml.title
    [PSCustomObject]@{
        Path      = $_.path
        Extension = $extension
        Title     = $title
    }
} | Export-Csv 'filepath' -NoTypeInformation

您也可以使用计算属性完成所有操作。

$SelectProps = @(
    "Path",
    @{n="Extension";e={$_.path -replace '.*\\Extensions\\'}},
    @{n="Title";e={(Invoke-webrequest -Uri "https://chrome.google.com/webstore/detail/$($_.path -replace '.*\\Extensions\\')" -Method Get).ParsedHtml.title}}
)

Import-Csv 'filepath' |
    Select-Object $SelectProps |
        Export-Csv 'filepath' -NoTypeInformation

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM