【问题标题】:If Else statement Powershell CSV with Output CSVIf Else 语句 Powershell CSV 和输出 CSV
【发布时间】:2018-09-07 03:05:52
【问题描述】:

我在 powershell 脚本方面相当陌生,需要有关 csv 格式的以下输出的帮助。我正在尝试选择一列,例如ACCOUNT.UPLOAD 和 make 和 if/else 语句将其输出到另一个 csv 文件中。请有人帮忙。

输出 csv 应如下所示:

$results = Import-Csv 'C:\Users\test\Desktop\Test\customer.csv' |
Select-Object "ACCOUNT.UPLOAD"

ForEach ($row in $results) 
{
    If ($row.Type0 -ne 'CP000101', 'CP000102')
    { 
        $row."ACCOUNT.UPLOAD" = "$($row.ACCOUNT.UPLOAD)"
        Write-Host $row."ACCOUNT.UPLOAD"
    }
}   
$results | Export-Csv C:\Users\test\Desktop\Test\test.csv -NoTypeInformation

谢谢

【问题讨论】:

  • (a) $results 包含只有 一个 属性的对象,即您使用Select-Object 提取的ACCOUNT.UPLOAD 属性。 (b) 因此,循环中的 $row 对象没有 Type0 属性(甚至不在您的 CSV 输入中)。 (c) -ne 的 RHS 不支持 arrays - 请改用运算符 -in。 (d) $row."ACCOUNT.UPLOAD" = "$($row.ACCOUNT.UPLOAD)" 是无操作的,因为从 CSV 文件中读取的所有内容都是以字符串开头的 - 你想做什么?请通过直接更新您的问题来澄清。

标签: powershell csv scripting


【解决方案1】:

这将为您提供所需的东西。添加了 cmets 来解释我做了什么。

$results = Import-Csv "C:\Users\test\Desktop\Test\customer.csv" | Select-Object "ACCOUNT.UPLOAD"
# Created array to be able to add individual results from foreach
$TheCSV = @()

ForEach ($row in $results) {
    # You can use a -ne in the right hand side, if done like this.
    If (($row.'ACCOUNT.UPLOAD' -ne 'CP000101') -and $row.'ACCOUNT.UPLOAD' -ne 'CP000102') {
        # Adds the ROW column to the entry and finds the index that it was in from $results.
        # Did a +2 as it does not include the header and it starts at value 0. So to match it up with the actual excel row numbers, add 2.
        $row | Add-Member -Name 'ROW' -type NoteProperty -Value "$([array]::IndexOf($results.'ACCOUNT.UPLOAD',$row.'ACCOUNT.UPLOAD')+2)"
        $TheCSV += $row
    }
}
$TheCSV | Export-Csv "C:\Users\test\Desktop\Test\test.csv" -NoTypeInformation

【讨论】:

  • 哇,先生!你让我今天一整天都感觉很好!谢谢你
【解决方案2】:

使用 PowerShell 方式:

param(
    [Parameter(Position=0)]
    $InputFile = 'D:\\Temp\\Data.csv',
    [Parameter(Position=1)]
    $OutputFile = 'D:\\Temp\\Output.csv'
)

Import-Csv $InputFile |
    Select-Object "ACCOUNT.UPLOAD" |
    %{
        $lineno++
        if ($_.'ACCOUNT.UPLOAD' -notin @('CP000101', 'CP000102')) {
            $_ | Add-Member -Name 'ROW' -type NoteProperty -Value $lineno
            $_ # Output to pipeline
        }
    } -Begin { $lineno = 1 } |
    Export-Csv $OutputFile -NoTypeInformation

使用:

.\Script.ps1

.\Script.ps1 inputfilename.csv outputfilefname.csv

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-25
    • 2021-11-24
    • 2017-09-25
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多