如果Else声明Powershell CSV

时间:2017-06-14 14:13:42

标签: powershell csv if-statement

当我运行我的代码时,它会给我以下错误。 Error 我所拥有的代码是将csv然后过滤名称列只是管理员,然后我有标题列过滤我提供的所有操作系统。 if语句表示如果列Type0等于域,则输入"唯一帐户名"列在Account0之后的Domain0。否则它将把它放在Netbios名称中,然后是Account0。下面是excel表。以及每个的期望输出。 Excel Sheet Desired output of Unique Account Name

 Import-Csv 'U:\Local Group Members.csv' | where-Object {($_.Name0 -eq "administrators") -and ($_.caption0 -match "Microsoft Windows 10 Enterprise|Microsoft Windows 7 Enterprise|Microsoft Windows 7 Professional|Microsoft Windows 8 Enterprise|Microsoft Windows 8 Pro|Microsoft Windows 8.1 Enterprise|Microsoft Windows 8.1 Pro")} |
Select-Object "Netbios_name0", "Name0", "Account0","category0","Domain0","Unique Account Name","Type0","caption0", "Excluded" |
ForEach-Object 

If ($_.Type0 -eq 'Domain') { 
    $_.UniqueAccountName = "$($_.Domain0) - $($_.Account0)" 
} Else { 
    $_.UniqueAccountName = "$($_.Netbios_name0) - $($_.Account0)" 
}

Export-Csv -notypeinformation U:\LGMbestone.csv

我是一个PowerShell新手,我被卡住了,我怎么能让这个代码运行?

2 个答案:

答案 0 :(得分:2)

你不能管道到if语句,并且你需要逐行迭代结果来修改对象,这需要一个foreach循环。另外,Export-CSV的管道优于使用输入对象调用它。以下是基于您的代码的示例。希望这有帮助!

    $csv = Import-Csv 'U:\Local Group Members.csv' |
Where-Object {($_.Name0 -eq "administrators") -and ($_.caption0 -match "Microsoft Windows 10 Enterprise|Microsoft Windows 7 Enterprise|Microsoft Windows 7 Professional|Microsoft Windows 8 Enterprise|Microsoft Windows 8 Pro|Microsoft Windows 8.1 Enterprise|Microsoft Windows 8.1 Pro")} |
Select-Object "Netbios_name0", "Name0", "Account0","category0","Domain0","Unique Account Name","Type0","caption0", "Excluded"

#Modify each line based on your parameters
Foreach ($row in $csv) {
    If ($row.Type0 -eq 'Domain') { 
        $row."Unique Account Name" = "$($row.Domain0) - $($row.Account0)" 
        Write-Host $row."Unique Account Name"
    } Else { 
        $row."Unique Account Name" = "$($row.Netbios_name0) - $($row.Account0)"
    }
}

#Export CSV
$csv | Export-Csv C:\LGMbestone.csv -NoTypeInformation

答案 1 :(得分:0)

看起来像一个格式问题。对于foreach,它应该是这样的:

$import=Import-Csv 'U:\Local Group Members.csv' | where-Object {($_.Name0 -eq "administrators") -and ($_.caption0 -match "Microsoft Windows 10 Enterprise|Microsoft Windows 7 Enterprise|Microsoft Windows 7 Professional|Microsoft Windows 8 Enterprise|Microsoft Windows 8 Pro|Microsoft Windows 8.1 Enterprise|Microsoft Windows 8.1 Pro")} |
Select-Object "Netbios_name0", "Name0", "Account0","category0","Domain0","Unique Account Name","Type0","caption0", "Excluded" 

ForEach($imp in $import)
{ 

    If ($imp.Type0 -eq 'Domain') 
    { 
        $imp.UniqueAccountName = "$($imp.Domain0) - $($imp.Account0)" 
    } 
    Else 
    { 
        $imp.UniqueAccountName = "$($imp.Netbios_name0) - $($imp.Account0)" 
    }

    Export-Csv "$imp.UniqueAccountName" -notypeinformation "U:\LGMbestone.csv" -Append
}

注意:我没有检查import-csv部分。我相信它正确地获取数据,你应该使用foreach循环迭代每一行值