I would like to make a PowerShell script trigger other scripts based on the existence of *.mp4
files in subfolders of a parent folder.
The question is the following: I have a folder called "Cut" inside that folder I have other folders that follow the logic Model 01
, Model 02
, Model 03
...
Inside each Model XX
folder I have a .ps1
script that I would like to be triggered every time there is a .mp4
file inside it.
The main point is that this script would have to be called in a new instance, not inside the main script.
What's the best way to do this?
What I've come up with so far is this:
Get-ChildItem -Path "$env:USERPROFILE\Desktop\Cut" -Recurse -Filter "*.mp4" -ea 0 | ForEach-Object {
Start-Process powershell ".\ffmpeg.ps1"
}
CodePudding user response:
I suggest inverting the logic by searching for all ffmpeg.ps1
files, and filtering them by whether at least one *.mp4
is present alongside each:
Get-ChildItem -Path $env:USERPROFILE\Desktop\Cut -Recurse -Filter ffmpeg.ps1 |
Where-Object { Test-Path (Join-Path $_.DirectoryName *.mp4) } |
ForEach-Object {
Start-Process -WorkingDirectory $_.DirectoryName powershell.exe "-NoExit -File `"$($_.FullName)`""
}
Inverting the logic ensures that you call a given directory's
ffmpeg.ps1
file only once, whereas invoking it once for each*.mp4
file in that directory, which is what your own approach attempted, is probably undesired.The
-WorkingDirectory
parameter ofStart-Process
is used to set the working directory to the respectiveffmpeg.ps1
's directory.The
-File
parameter ofpowershell.exe
, the Windows PowerShell CLI, is used to invoke each target script, which is the preferred way to invoke script files (without it ,powershell.exe
defaults to-Command
, which behaves subtly differently)- See this answer for guidance on when to use
-File
vs.-Command
.
- See this answer for guidance on when to use
-NoExit
is additionally passed so as to keep the window of the newly launched process open after the script terminates, to allow you to examine the results.
CodePudding user response:
Get-ChildItem -Path "$env:USERPROFILE\Desktop\Cut" -Recurse -Filter "*.mp4" -ea 0 | ForEach-Object {
Invoke-Item (start powershell (Split-Path $_.FullPath "\ffmpeg.ps1 $_.Name")
}
The first part seems quit alright to me. Secondly you can invoke your script using the path of of the matched file (split-path) but u also want to to to hand over the target file to the script as paramenter in the end.