无法使用Powershell脚本发送带有附件的电子邮件

时间:2020-06-19 14:28:01

标签: powershell

我有一个脚本,每30分钟运行一次该脚本。如果文件夹中有文件,则此脚本应发送电子邮件。我的问题是,我收到一个错误消息:“该文件正在被另一个进程使用...”,即“ Send-MailMessage @Msg”

我该如何解决?

$Email       = "myemail"
$Internal    = "cc"
$Subject     = "Form"

[array]$attachments = Get-ChildItem "\\ip\ftp$\c\1\files\Backorder" *.err

if ([array]$attachments -eq $null) {
}

else {

$Msg = @{
    to          = $Email
    cc          = $Internal
    from        = "address"
    Body        = "some text"

    subject     = "$Subject"
    smtpserver  = "server"
    BodyAsHtml  = $True
    Attachments = $attachments.fullname
}

Send-MailMessage @Msg

Start-Sleep -Seconds 1800

}

1 个答案:

答案 0 :(得分:1)

您需要构建测试以查看文件是否被锁定(仍在写入中)。为此,您可以使用以下功能:

function Test-LockedFile {
    param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('FullName', 'FilePath')]
        [string]$Path
    )
    $file = [System.IO.FileInfo]::new($Path)
    # old PowerShell versions use:
    # $file = New-Object System.IO.FileInfo $Path

    try {
        $stream = $file.Open([System.IO.FileMode]::Open,
                             [System.IO.FileAccess]::ReadWrite,
                             [System.IO.FileShare]::None)
        if ($stream) { $stream.Close() }
        return $false
    }
    catch {
        return $true
    }
}

将其放置在当前代码上方的某个位置,您可以执行以下操作:

$Email    = "myemail"
$Internal = "cc"
$Subject  = "Form"

# get the fullnames of the *.err files in an array
$attachments = @(Get-ChildItem -Path "\\ip\ftp$\c\1\files\Backorder" -Filter '*.err' -File)

if ($attachments.Count) {
    # wait while the file(s) are locked (still being written to)
    foreach ($file in $attachments) {
        while (Test-LockedFile -Path $file.FullName) {
            Start-Sleep -Seconds 1
        }
    }

    $Msg = @{
        To          = $Email
        Cc          = $Internal
        From        = "address"
        Body        = "some text"
        Subject     = $Subject
        SmtpServer  = "server"
        BodyAsHtml  = $True
        Attachments = $attachments.FullName
    }

    Send-MailMessage @Msg

    Start-Sleep -Seconds 1800
}

希望有帮助