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

无法使用powershell脚本发送带有附件的电子邮件,powershell,Powershell,我有一个脚本,每30分钟运行一次。如果文件夹中有文件,此脚本应发送电子邮件。我的问题是,我得到一个错误:该文件正在被另一个进程使用。。。这是sendmailmessage@Msg 我怎样才能解决这个问题 $Email = "myemail" $Internal = "cc" $Subject = "Form" [array]$attachments = Get-ChildItem "\\ip\ftp$\c\1\files\Backorder" *.err if ([

我有一个脚本,每30分钟运行一次。如果文件夹中有文件,此脚本应发送电子邮件。我的问题是,我得到一个错误:该文件正在被另一个进程使用。。。这是sendmailmessage@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

}

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

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
}
希望有帮助