[英]Powershell Script started by Task Scheduler not working
So I´ve got a powershell script that checks if a folder was created in a specific directory and then does stuff with that folder 所以我有一个Powershell脚本,该脚本检查是否在特定目录中创建了文件夹,然后对该文件夹进行了处理
Code: 码:
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>
}
Starting this script manually works perfect but running it with the Task Scheduler is not working. 手动启动此脚本可以完美运行,但无法使用“任务计划程序”运行它。
First I tried starting the script directly which shows that the script was successfully started but nothing that happens -Action { ... }
gets executed. 首先,我尝试直接启动脚本,这表明脚本已成功启动,但未发生任何事情
-Action { ... }
被执行。
I then tried to make a batch that starts the powershell script which gets started by the Task (as suggested here How to run a PowerShell script from a batch file ) 然后,我尝试制作一个启动Powershell脚本的批处理,该脚本由Task启动(如此处的建议如何从批处理文件运行PowerShell脚本 )
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\PathtoScript\Script.ps1""' -Verb RunAs}"
but the problem still is the same. 但是问题仍然是一样的。
The script starts (Wrote some Output to a file to check that) but nothing inside -Action { ... }
gets executed. 脚本启动(将一些输出写入文件以进行检查),但
-Action { ... }
内部-Action { ... }
执行任何操作。
Edit: Task Schedular is set to run the script as a user with admin privileges as the actions that do not work need those, writing to C:\\ works perfectly fine 编辑:Task Schedular设置为以具有管理员特权的用户身份运行脚本,因为不起作用的操作需要这些操作,写入C:\\可以很好地工作
Scheduled task action: 计划任务动作:
Program Script (Use the full path): 程序脚本(使用完整路径):
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments ([NOT]optional): 添加参数([NOT]可选):
-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:\PathtoScript\Script.ps1" -Any 'other' -arguments 'you need' -should follow
Ok I found my mistake 好吧,我发现了我的错误
As @PetSerAl suggested I forgot that the FileSystemWatcher
Acts only in scope of that one specific process of the script. 正如@PetSerAl所建议的那样,我忘记了
FileSystemWatcher
仅在脚本的该特定过程的范围内起作用。 The Script has started the Job successfully but after closing the process of the script (aka. the window I started the script in) the Job broke down because it could not refer to FileSystemWatcher
anymore. 脚本已成功启动了作业,但是在关闭脚本进程(也就是我在其中启动脚本的窗口)后,该作业崩溃了,因为它不再引用
FileSystemWatcher
。
Adding something simple like: 添加一些简单的内容,例如:
Do{
$JobExist = Get-Job
} while($JobExist -ne '')
worked perfectly fine 工作得很好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.