【问题标题】:How can I add string and create new column in my csv file using PowerShell如何使用 PowerShell 在 csv 文件中添加字符串并创建新列
【发布时间】:2022-01-13 23:07:51
【问题描述】:

在我现有的 CSV 文件中,我有一个名为“SharePoint ID”的列,它看起来像这样

1.ylkbq
2.KlMNO
3.
4.MSTeam
6.
7.MSTEAM
8.LMNO83

我只是想知道如何在我的 CSV 调用“SharePoint 电子邮件”中创建一个新列,然后将“@gmail.com”添加到“ylkbq”、“KLMNO”和“LMNO83”等实际 ID而不是在空白处也适用于所有。并且可能不会将“MSTEAM”添加/转移到新列,因为它不是 Id。


$file = "C:\AuditLogSearch\New folder\OriginalFile.csv"
$file2 = "C:\AuditLogSearch\New folder\newFile23.csv"

$add = "@GMAIL.COM"

$properties = @{
    Name       = 'Sharepoint Email'
    Expression = {
        switch -Regex ($_.'SharePoint ID') {
    
          #Not sure what to do here
        }
    }
}, '*' 
Import-Csv -Path $file | 
Select-Object $properties |
Export-Csv $file2 -NoTypeInformation

【问题讨论】:

    标签: powershell csv powershell-2.0


    【解决方案1】:

    calculated propertiesSelect-Object 一起使用是这样的:

    $add = "@GMAIL.COM"
    
    $expression = {
        switch($_.'SharePoint ID')
        {
            {[string]::IsNullOrWhiteSpace($_) -or $_ -match 'MSTeam'}
            {
                # Null value or mathces MSTeam, leave this Null
                break
            }
            Default # We can assume these are IDs, append $add
            {
                $_.Trim() + $add
            }
        }
    }
    
    Import-Csv $file | Select-Object *, @{
        Name = 'SharePoint Email'
        Expression = $expression
    } | Export-Csv $file2 -NoTypeInformation
    

    样本输出

    Index SharePoint ID SharePoint Email
    ----- ------------- ----------------
    1     ylkbq         ylkbq@GMAIL.COM
    2     KlMNO         KlMNO@GMAIL.COM
    3                   
    4     MSTeam        
    5                   
    6     MSTEAM        
    7     LMNO83        LMNO83@GMAIL.COM
    

    更简洁的表达方式,由于我看错了点,可以简化为只有一个if语句:

    $expression = {
        if(-not [string]::IsNullOrWhiteSpace($_.'SharePoint ID') -and $_ -notmatch 'MSTeam')
        {
            $_.'SharePoint ID'.Trim() + $add
        }
    }
    

    【讨论】:

    • 嗨@Santiago,再次非常感谢您,但只是想知道如何不在新列中包含“MSTeam”,因为它不是实际的 ID,也没有电子邮件。稍后我将需要使用新列获取 AzureAD displayName,因此即使在新列中包含“MSTeam”字样也可能会在以后给我带来问题。
    • @aaselab 那是我的错,我看错了,以为你想要 MSTeam 但没有附加。查看我的编辑。
    • 很抱歉再次打扰您,但我正在做我想做的漫长过程,直到现在我才发现有一个简单的过程,所以你介意看一下我的帖子一次再次stackoverflow.com/questions/70294010/… 非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多