在PowerShell脚本中删除特定字符之前的文本

时间:2019-04-24 06:03:47

标签: powershell sharepoint trim

我将SharePoint列表中的项目导出到数组中,然后将它们放入表中的电子邮件中。 SharePoint名称字段在显示名称之前提供了其他字符(我认为是用户ID),在将其输出到数组然后添加到电子邮件之前,我无法对其进行裁剪/删除。

我尝试使用以下几种变体,但我认为它不适用于已创建的数组:

(Get-Content $outputfile) |
    Select-String -Pattern '*#' -NotMatch |
    Out-File $outputfile

以及:

(Get-Content $outputfile) |
    Where-Object { $_.Trim() -ne "" } |
    Set-Content $outputfile

该脚本如下所示:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$web = Get-SPWeb -Identity "https://sharepointsite.com"
$list = $web.Lists["testlist"]

#Array to Hold Result - PSObjects
$ListItemCollection = @()

$list.Items | foreach {
    $ExportItem = New-Object PSObject 
    $ExportItem | Add-Member -MemberType NoteProperty -Name "Name" -Value $_["Name"]
    $ExportItem | Add-Member -MemberType NoteProperty -Name "Reason" -Value $_["Reason"]
    $ExportItem | Add-Member -MemberType NoteProperty -Name "Example" -Value $_["Example"]
    $ExportItem | Add-Member -MemberType NoteProperty -Name "Created" -Value $_["Created"]

    $ListItemCollection += $ExportItem
}

$web.Dispose()

$emailbody = $(cat C:\temp\emailbody.txt) + $ListItemCollection

#Email formatting
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "</style>"

$SMTPServer = "mail.com"
$EmailFrom = "test@mail.com" 
$EmailTo = "joel@mail.com"
$EmailSubject = "Test Email"

$Message = New-Object System.Net.Mail.MailMessage $EmailFrom, $EmailTo
$Message.Subject = $EmailSubject
$Message.IsBodyHTML = $true
$message.Body = $emailbody + ($ListItemCollection | ConvertTo-Html -Head $style | Out-String)
$SMTP = New-Object Net.Mail.SmtpClient($SMTPServer)
$SMTP.Send($Message)

示例表输出显示:

Name          Reason              Example         Created
64;#Test User   testing reason    testing example   17/04/2019 4:28:33 a.m.
105;#John Smith test for reason   more testing for example more testing for example more testing for example    17/04/2019 4:29:24 a.m.

1 个答案:

答案 0 :(得分:0)

如果问题仅在于删除用户名前缀的多余字符,则可以使用

删除这些字符
$ExportItem | Add-Member -MemberType NoteProperty -Name "Name" -Value ($_["Name"] -replace '^\d+;#')

顺便说一句,如果您使用的是PowerShell 3.0或更高版本,则有一种更简单的方法来构造对象

$ListItemCollection = $list.Items | ForEach-Object {
    [PSCustomObject]@{
        'Name'    = $_["Name"] -replace '^\d+;#'
        'Reason'  = $_["Reason"]
        'Example' = $_["Example"]
        'Created' = $_["Created"]
    }

甚至(未经测试)

$ListItemCollection = $list.Items | Select-Object @{Name = 'Name'; Expression = {$_["Name"] -replace '^\d+;#'}},
                                                  Reason, Example, Created

希望这会有所帮助