首页 > 解决方案 > Powershell如何根据正则表达式仅替换特定列的CSV文件中的值

问题描述

我一直在尝试找到解决这个问题的方法,我正在从一个更大的文件创建一个 CSV,选择特定的列,我从这里得到了很大的支持,并且该任务正在完成,但是我的 CSV 文件包含我的值想替换,例如,“用户名”列,我只想保留 1 个用户,这意味着删除“,”之后的所有内容,我得到了一个看起来像
(,.*$)|(not applicable)|(sscope)

这就是我想用空字符串替换的内容,但我无法让它工作,它有时会删除所有内容。

用户名列中的值如下所示

User Name

B2 cell : not applicable
B3 cell : sscope, sscope
B4 cell : sscope
B5 cell : sscope, sscope, hernhng002, coanbvf001, clacbff01, polsbvcw04, taylor38, milthy12, hic6yth31, carruhgy58, grabngh09, starytht37, milytht937
B6 cell : tamyhg4647adm
B7 cell : moreduj4664

问题 2:如何根据公共键(两者中的名称列)添加来自不同 CSV 文件的列,但只有一个文件具有内存列,我想将其添加到第一个文件中。谢谢



. D:\Data\BF_Scripts\Write-Log.ps1


    $filePath = "D:\Data\Input\bigFixDataNew.csv"

    #$filePath = "D:\Data\Input\BF_Test_Dec2019.csv"

    $System = "D:\Data\Output\System.csv"


    $desiredColumnsSystem = @{ expression = {$_.'Internal Computer ID'}; label = 'RESOURCEID' },
    @{ expression = {$_.'Computer Name'}; label = 'NAME'},
    @{ expression = {$_.'DNS Name'}; label = 'DOMAIN'},
    @{ expression = {$_.'DNS Name'}; label = 'USER_DOMAIN'},
    @{ expression = {$_.'User Name'}; label = 'USER_NAME'}

    $Regex = '(,.*$)|(, sscope)|(sscope)'

    Try {
        Write-Log -Message 'Starting Creation of System CSV...'

        Import-Csv $filePath | Select-Object $desiredColumnsSystem | Sort RESOURCEID -Unique |
        Export-Csv -Path $System –NoTypeInformation



        $content = Get-Content $System 

        $content |  ForEach-Object {$_ -replace $Regex,''}  | Set-Content $System 

        $size = ((Get-Item $system).length/1KB)
        $lastTouchedDate = (Get-Item $system).LastWriteTime



        Write-Log -Message  "Created the System CSV Successfully !! The size of $system is $size KB and the last write time was $lastTouchedDate"
    }

    catch
    {
        Write-Log -Message $_.Exception.Message
    }

标签: regexpowershellcsv

解决方案


这似乎已经做到了,再次感谢大家

Import-Csv $filePath | Select-Object $desiredColumnsSystem | Sort RESOURCEID -Unique | ForEach-Object {
            If ($_.USER_NAME -match $Regex) {
                $_.USER_NAME = $_.USER_NAME -replace $Regex,''
            }
            $_
        } |
        Export-Csv -Path $System –NoTypeInformation

推荐阅读