从批处理文件在Powershell ISE中运行脚本

时间:2018-10-29 09:41:25

标签: powershell batch-file powershell-ise

我正在执行我的批处理文件,该文件将打开Powershell ISE并加载脚本,但是什么也不做...我仍然需要手动运行。我在这里想念东西吗?

BatchFile调用Powershell:

Powershell_ise.exe C:\Users\Desktop\myscript.ps1

该代码用于监视文件夹中的文件更改并发送电子邮件:

Function Register-Watcher {
    param ($folder)
    $filter = "logfile.txt" #all files
    $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{ 
        IncludeSubdirectories = $false
        EnableRaisingEvents = $true
    }

    $changeAction = [scriptblock]::Create('
        # This is the code which will be executed every time a file change is detected
        $path = $Event.SourceEventArgs.FullPath
        $name = $Event.SourceEventArgs.Name
        $changeType = $Event.SourceEventArgs.ChangeType
        $timeStamp = $Event.TimeGenerated 
        Write-Host "The file $name was $changeType at $timeStamp"
        Send-email
    ')

    Register-ObjectEvent $Watcher "Changed" -Action $changeAction
}

Function Send-email{

    $SMTPServer = "smtp.gmail.com"
    $SMTPPort = "587"
    $Username = "*****@gmail.com"
    $Password = "*******"

    $to = "*****@gmail.com"
    $subject = "Email Subject"
    $body = "Insert body text here"
    $attachment = "C:\Users\Desktop\AccountMapping.sdl"

    $message = New-Object System.Net.Mail.MailMessage
    $message.subject = $subject
    $message.body = $body
    $message.to.add($to)
    $message.from = $username
    $message.attachments.add($attachment)

    $smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
    $smtp.EnableSSL = $true
    $smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
    $smtp.send($message)
    Write-Host "Mail Sent"
}

 Register-Watcher "C:\Users\Desktop"

0 个答案:

没有答案