首页 > 解决方案 > 合并脚本并更新 csv 文件

问题描述

我如何将这两者结合起来,以获得输出Jose is a Boy并在 csv 文件上更新它。

cls
$response = Read-Host -prompt "Do you want to update a csv file? Yes/No" 
#to get input from the user
If ($response -eq "Yes")
{
   $csvfile = Read-Host "Enter a csv filename" #to get the csv filename
   Import-Csv $csvfile
   
}
else {
   Write-Host "Exit."
}

和这个

Import-Csv -Path $csvfile | ForEach-Object {
    If ($_.ColumnA -eq 'Jose'){
        $_.ColumnB = 'Boy'    
    }
    else{
        $_.ColumnB = 'Girl'
    }
    $_
} | Format-Table -AutoSize

输出必须是这样的:

Do you want to update csv file? Yes/No
Enter csv filename: example.csv

ColumnA ColumnB
------- -------
Jose    Boy
Maria   Girl
Jose    Boy
Maria   Girl
Jose    Boy
Jose    Boy
Jose    Boy
Maria   Girl 

标签: powershellpipeline

解决方案


我认为这就是您要查找的内容,我在代码中添加了注释以帮助您理解。

$ErrorActionPreference = 'Stop'

cls
$response = Read-Host -prompt "Do you want to update a csv file? Yes/No" 
#to get input from the user

if($response -eq 'No'){break} # This will end your script.

# A cool way to ask a user to select a file is a OpenFileDialog
# with this you make it easier to find the file you're looking for
# if you still prefer the Read-Host method, uncomment below line
# and remove the OpenFileDialog code.

# $csvfile = Read-Host "Enter a csv filename"

# Remove from here
Add-Type -AssemblyName System.Windows.Forms

$browse = New-Object System.Windows.Forms.OpenFileDialog -Property @{ 
    InitialDirectory = [environment]::GetFolderPath('MyDocuments')
    Filter = 'Comma Separated Value File (*.csv)|*.csv'
    Multiselect = $false
}
$browse.ShowDialog() > $null

# If no file was selected (Cancel button or Close button)
# end the program
if(-not $browse.FileName){break}

# Up to here if you do not wish to use this method.

# If using OpenFileDialog use this:
$csv = Import-Csv $browse.FileName

# If using Read-Host use this:
$csv = Import-Csv $csvfile

$newCsv = $csv | foreach-object {

    if($_.ColumnA -eq 'Jose')
    {
        # Using a Try {} Catch {} block in the conditions because
        # if the CSV does not contain a Column with name 'ColumnB'
        # doing $_.ColumnB = 'Boy' would throw an error.
        try
        {
            $_.ColumnB = 'Boy'
        }
        catch
        {
            # The Catch block here will handle the error by adding a new 'Member'
            # to the object with the desired Value and the desired Column Name.
            $_ | Add-Member -MemberType 'NoteProperty' -Name 'ColumnB' -Value 'Boy'
        }
    }
    else
    {
        try
        {
            $_.ColumnB = 'Girl'
        }
        catch
        {
            $_ | Add-Member -MemberType 'NoteProperty' -Name 'ColumnB' -Value 'Girl'
        }
    }

    $_
}

# Here you can see the result of the new CSV
$newCsv | Format-Table

# In case you need to export these to a new CSV or replace the existing one
$newCsv | Export-Csv 'path/to/newCsv.csv' -NoTypeInformation

推荐阅读