1

That's probably a simple question for someone who knows Powershell. I have already tried to implement the suggestions of several answers to similar questions, such as these and these. I have a filewatcher that monitors a folder and writes a log file in case of changes. This works well.

What I didn't manage to do is to execute an additional Python script. I am grateful for any advice.

$folder = 'F:\myPath\myFolder' # Enter the root path you want to monitor.
$filter = '*.*'  # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $true if required.                          
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

# Registered events:
Register-ObjectEvent $fsw Renamed -SourceIdentifier FileRenamed -Action {
$OldName = $Event.SourceEventArgs.OldName
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
Out-File -FilePath F:\myPath\myLogFile.txt -Append -InputObject "The file $name was $changeType at $timeStamp"
python F:\myPath\myPythonScript.py}

How can I achieve this with Powershell ISE?

Chris
  • 33
  • 4

1 Answers1

1

You'll have much more luck using the Powershell console than you will the ISE. If you have Python added to your PATH, then it's as simple as python F:\myPath\myPythonScript.py

If the Python script returns any values, in order to pass them back to Powershell, you need to print them to the screen and they will be stored as an array in the order they're returned.

James Whitehead
  • 101
  • 1
  • 11
  • You are right: If I only enter the command `python F:\myPath\myPythonScript.py` into the console, the Python script runs. But when I run the whole script (including the filesystemwatcher) in the Powershell console, the Python script does not run when I change a file in the watched folder. So how do I get the Python script to run if a file is changed in the watched folder? – Chris Nov 29 '17 at 08:23
  • All an EventSubscriber does is execute the code in the braces following `-Action`. Does the code in there execute correctly? Does it write to the log file, for example? – James Whitehead Nov 29 '17 at 09:34
  • Yes,the code executes correctly and it writes the log file.But it doesn't execute the python script in the console. I edited the question and the code that I am using. – Chris Nov 29 '17 at 11:16
  • What's the contents of the Python script? – James Whitehead Nov 29 '17 at 11:45
  • This is the content of the Python script: `# -*- coding: utf-8 -*- print "Hello World!"` – Chris Nov 29 '17 at 12:20