Reputation: 17
I have a powershell script designed for logging that is triggered and run through a scheduled task. The problem is the script will not write to file when run in this way. If i run it through cmd it works perfectly. I have tried giving the script highest privileges and I am passing the exact location of the log-file as an argument when I run the script. Neither have solved the issue. Please can someone help? See code:
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
}
Command:
Powershell.exe Add arguments: -ExecutionPolicy Bypass F:\FTU-E2\Scripts\monitor.ps1 -inputPath F:\FTU-E2\RejectPaths.txt -logfilelocation "F:\FTU-E2\Log.txt"
Upvotes: 0
Views: 1259
Reputation: 4742
If the task is set to run under the SYSTEM account, or really any account other than your account, it is hanging up at the $username = F:\FTU-E2\PsLoggedon.exe -l
because PsLoggedon is waiting for a user to accept the EULA, which appears the first time a user runs it on a machine.
You can bypass the EULA with the -accepteula
command:
$username = C:\temp\PsLoggedon.exe -l -accepteula
Once I made this change, it ran fine whether the task was set to run with my account or the SYSTEM account.
Also, you can remove the infinite loop at the bottom of the script and use the -NoExit
switch on the PowerShell command so that the process isn't ended.
-ExecutionPolicy Bypass -NoExit ...
Upvotes: 1