【问题标题】:Append same string to all variables in column of CSV in powershell将相同的字符串附加到PowerShell中CSV列中的所有变量
【发布时间】:2021-03-23 06:05:35
【问题描述】:

我需要有关如何将字符串 -Config 添加到名称列中的每个名称的帮助。

CSV 文件包含:

FullName             Name    LastWriteTime
\\remotecomputer\    Henry   4/30/2020  3:44:57 PM
\\remotecompter\     Magy    12/7/2020  9:04:28 PM

想要的输出:

FullName             Name    LastWriteTime
\\remotecomputer\    Henry-Config   4/30/2020  3:44:57 PM
\\remotecompter\     Magy-Config    12/7/2020  9:04:28 PM

我当前的代码:

$InvoiceList = Import-CSV -Path C:\$source-PREP.csv | foreach($list in $InvoiceList){
$Name=$($list.name)
Get-ChildItem -Path 'C:\Names' -Filter *.txt | where {$_.Name -like '*' }|Copy-Item -Destination 'c:\newfolder' -Force }

【问题讨论】:

    标签: powershell for-loop replace each


    【解决方案1】:

    由于您的文件只有几个已知列,您可以使用Select-Object 并使用calculated property-Config 附加到名称列中的值:

    $data = Import-CSV -Path "C:\$source-PREP.csv" | 
            Select-Object FullName, @{Name = 'Name'; Expression = {'{0}-Config' -f $_.Name}}, LastWriteTime
    $data | Export-Csv -Path "C:\$source-PREP.csv" -NoTypeInformation -Force
    

    结果

    FullName          Name         LastWriteTime    
    --------          ----         -------------    
    \\remotecomputer\ Henry-Config 4/30/2020 3:44:57
    \\remotecompter\  Magy-Config  12/7/2020 9:04:28
    

    【讨论】:

      【解决方案2】:

      您只需要迭代 CSV 中的每一行并更新 name 属性。完成后导出回 CSV

      $csvfile = 'some\path\to\file.csv'
      
      $csvdata = Import-Csv $csvfile
      
      $csvdata | ForEach-Object {$_.name = $_.name + '-Config'}
      
      $csvdata | Export-Csv $csvfile -NoTypeInformation
      

      【讨论】:

        猜你喜欢
        • 2011-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-09
        • 2014-02-17
        • 1970-01-01
        • 2016-07-14
        • 1970-01-01
        相关资源
        最近更新 更多