Reputation: 175
I tried to use the code of this post.
When I use this code directly on PowerShell terminal it run correctly.
Add-Type -AssemblyName presentationCore
$filepath = "C:\Temp\test\Wildlife.wmv"
$wmplayer = New-Object System.Windows.Media.MediaPlayer
$wmplayer.Open($filepath)
Start-Sleep 2
$duration = $wmplayer.NaturalDuration.TimeSpan.Seconds
$wmplayer.Close()
start playing
$proc = Start-process -FilePath wmplayer.exe -ArgumentList $filepath -PassThru
But when I run the code on .bat file, a cmd window appears and disappears in a few seconds and without further action.
If I run the .bat file on CMD, this errors appear:
The code inserted in .bat file is:
Add-Type -AssemblyName presentationCore
$filepath = [uri] "C:\Users\??????\Desktop\small.mp4"
$wmplayer = New-Object System.Windows.Media.MediaPlayer
$wmplayer.Open($filepath)
Start-Sleep 2 # This allows the $wmplayer time to load the audio file
$duration = $wmplayer.NaturalDuration.TimeSpan.TotalSeconds
$wmplayer.Play()
Start-Sleep $duration
$wmplayer.Stop()
$wmplayer.Close()
I would be most thankful if you could help me solving this problem.
Thanks.
Upvotes: 3
Views: 9620
Reputation: 23385
You are attempting to run PowerShell commands within a .bat file (as a result the PowerShell engine isn't being used to execute the code so the commands fail).
You need to save the script as a .ps1 file, then execute it from the command-line either via it's full path name or by changing to the directory where the script exists and entering:
.\scriptname.ps1
Where scriptname is the name you saved the file at.
If you want to execute the script via a .bat file, you still need to save it as a .ps1 and then create a .bat file with the following content:
Powershell.exe -File C:\path\to\my\script\myscript.ps1
Obviously correcting the path accordingly. Note there is no advantage to running the script this way, but one reason you might use a .bat file is if you needed to change the execution policy to allow script execution (I don't think you do in your case) as follows:
Powershell.exe -executionpolicy unrestricted -File C:\path\to\my\script\myscript.ps1
Upvotes: 1