簡體   English   中英

Powershell 如何僅基於正則表達式為特定列替換 CSV 文件中的值

[英]Powershell How to Replace value in CSV File for only specific column based on Regex

我一直在試圖找到這個問題的解決方案,我正在從一個更大的文件創建一個 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 文件的列,但只有 1 個文件具有內存列,我想將其添加到第一個文件中。 謝謝



. 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
    }

這似乎已經做到了,再次感謝大家

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM