如何使用 PowerShell 在我的 csv 文件中添加字符串并创建新列

How can I add string and create new column in my csv file using PowerShell

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

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

我只是想知道如何在我的 CSV 调用“SharePoint 电子邮件”中创建一个新列,然后仅将“@gmail.com”添加到实际 ID,如“ylkbq”、“KLMNO”和“LMNO83”,而不是应用于空白 space 中的所有内容。可能不会 add/transfer “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

使用 calculated properties with Select-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
    }
}