我有一个PowerShell脚本,用于记录被触发并在计划任务中运行的日志。问题是当以这种方式运行时脚本不会写入文件。如果我通过cmd运行它它完美地工作。我试过给脚本最高权限,我在运行脚本时将日志文件的确切位置作为参数传递。都没有解决这个问题。请有人帮忙吗?见代码:
Param([string]$inputPath, [string]$logfilelocation)
$i=0
$paths = Get-Content $inputPath; #Text file with list of file paths to monitor
$global:Logfile = $logfilelocation
foreach ($path in $paths)
{
$filter = '*.*' # You can enter a wildcard filter here.
# In the following line, you can change 'IncludeSubdirectories to $false if
# required to disable subfolder monitoring.
$fsw = New-Object IO.FileSystemWatcher $path, $filter -Property @{IncludeSubdirectories = $false; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
# Here, all four events are registerd. You need only subscribe to events that you need:
#File Created
Register-ObjectEvent $fsw Created -SourceIdentifier "$i+FileCreated" -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$username = F:\FTU-E2\PsLoggedon.exe -l
Write-Host "The file '$name' was $changeType by $username" -fore green
Out-File -FilePath $global:Logfile -Append -InputObject "The file '$name' was $changeType at $timeStamp by $username" -Force
}
++$i
}
while($true){
start-sleep -second 5
}
命令:
Powershell.exe Add arguments: -ExecutionPolicy Bypass F:\FTU-E2\Scripts\monitor.ps1 -inputPath F:\FTU-E2\RejectPaths.txt -logfilelocation "F:\FTU-E2\Log.txt"
答案 0 :(得分:1)
如果任务设置为在SYSTEM帐户下运行,或者实际上是帐户以外的任何帐户,则会挂起$username = F:\FTU-E2\PsLoggedon.exe -l
,因为PsLoggedon正在等待用户接受EULA,这似乎是用户第一次在计算机上运行它。
您可以使用-accepteula
命令绕过EULA:
$username = C:\temp\PsLoggedon.exe -l -accepteula
完成此更改后,无论任务是否设置为使用我的帐户或SYSTEM帐户运行,都可以正常运行。
此外,您可以删除脚本底部的无限循环,并使用PowerShell命令上的-NoExit
开关,以便该过程不会结束。
-ExecutionPolicy Bypass -NoExit ...