【问题标题】:How can I have my script running in the background continuously? [duplicate]如何让我的脚本在后台连续运行? [复制]
【发布时间】:2019-04-19 02:45:09
【问题描述】:

我有以下 powershell 脚本,每当创建新文件/将其复制到特定文件夹时,它都会发送一封电子邮件。 我面临的唯一问题是,每当我关闭 powershell 窗口时,脚本就会停止工作! 我需要脚本在后台运行,即使我已从服务器注销。我怎样才能做到这一点。 我正在运行 Windows Server 2012 R2

$folder = "C:\temp"
$mailserver = "172.33.33.33"
$recipient = "any@ddress.com"

$fsw = New-Object System.IO.FileSystemWatcher $folder -Property @{
   IncludeSubdirectories = $true
   NotifyFilter = [IO.NotifyFilters]'FileName'
}

$created = Register-ObjectEvent $fsw -EventName Created -Action {
   $item = Get-Item $eventArgs.FullPath
   $s = New-Object System.Security.SecureString
   $anon = New-Object System.Management.Automation.PSCredential ("NT 
    AUTHORITY\ANONYMOUS LOGON", $s)
  Send-MailMessage -To $recipient `
               -From "ann@ddress.com" `
                -Subject “KCC File Downloaded” `
                -Body "Hi Everyone" `
                -SmtpServer $mailserver `
                -Credential $anon
  } 

【问题讨论】:

  • 另请参阅我的答案here,它为您的任务奠定了良好的基础。 stackoverflow.com/questions/36846688/…
  • 您可以从系统管理员帐户打开命令提示符并从那里执行 PowerShell 吗?

标签: powershell automation background


【解决方案1】:

文件观察器的最佳选择是将脚本编写为 Windows 服务。即使您没有登录它也可以工作,并且您可以使用服务帐户来获得网络权限。 例如:https://msdn.microsoft.com/en-us/magazine/mt703436.aspx

或者您也可以将脚本放在计划任务中。 示例:https://social.technet.microsoft.com/wiki/contents/articles/38580.configure-to-run-a-powershell-script-into-task-scheduler.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2020-03-26
    • 2017-07-09
    • 2012-12-25
    • 2016-11-12
    • 1970-01-01
    相关资源
    最近更新 更多