簡體   English   中英

由Task Scheduler啟動的Powershell腳本不起作用

[英]Powershell Script started by Task Scheduler not working

所以我有一個Powershell腳本,該腳本檢查是否在特定目錄中創建了文件夾,然后對該文件夾進行了處理

碼:

echo "$(Get-Date -Format g) - Script started" >> C:\bitlocker.log

$folder = 'C:\Path\To\Check'

$filter = '*.*'           

$fsw = New-Object IO.FileSystemWatcher $folder, $filter 
$fsw.IncludeSubdirectories = $false              
$fsw.NotifyFilter = [IO.NotifyFilters]'DirectoryName' 

$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 

   $folderNow = $($EventArgs.FullPath)
   <do stuff now>

}

手動啟動此腳本可以完美運行,但無法使用“任務計划程序”運行它。

首先,我嘗試直接啟動腳本,這表明腳本已成功啟動,但未發生任何事情-Action { ... }被執行。

然后,我嘗試制作一個啟動Powershell腳本的批處理,該腳本由Task啟動(如此處的建議如何從批處理文件運行PowerShell腳本

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\PathtoScript\Script.ps1""' -Verb RunAs}"

但是問題仍然是一樣的。

腳本啟動(將一些輸出寫入文件以進行檢查),但-Action { ... }內部-Action { ... }執行任何操作。

編輯:Task Schedular設置為以具有管理員特權的用戶身份運行腳本,因為不起作用的操作需要這些操作,寫入C:\\可以很好地工作

計划任務動作:

程序腳本(使用完整路徑):

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

添加參數([NOT]可選):

-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:\PathtoScript\Script.ps1" -Any 'other' -arguments 'you need' -should follow

好吧,我發現了我的錯誤

正如@PetSerAl所建議的那樣,我忘記了FileSystemWatcher僅在腳本的該特定過程的范圍內起作用。 腳本已成功啟動了作業,但是在關閉腳本進程(也就是我在其中啟動腳本的窗口)后,該作業崩潰了,因為它不再引用FileSystemWatcher

添加一些簡單的內容,例如:

Do{
    $JobExist = Get-Job 
} while($JobExist -ne '')

工作得很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM