在 Windows 10 上使用 powershell 播放视频
Play video with powershell on Windows 10
我尝试使用 this post 的代码。
当我直接在 PowerShell 终端上使用此代码时,它 运行 正确。
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
但是当我 运行 .bat 文件上的代码时,cmd window 出现并在几秒钟内消失并且没有进一步的操作。
如果我运行 CMD 上的.bat 文件,出现这个错误:
enter image description here
.bat文件中插入的代码为:
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()
如果你能帮我解决这个问题,我将不胜感激。
谢谢。
您正在尝试 运行 .bat 文件中的 PowerShell 命令(因此没有使用 PowerShell 引擎来执行代码,因此命令失败)。
您需要将脚本保存为 .ps1 文件,然后通过其完整路径名或通过切换到脚本所在的目录并输入:
.\scriptname.ps1
其中 scriptname 是您保存文件的名称。
如果你想通过.bat文件执行脚本,你仍然需要将它保存为.ps1,然后创建一个包含以下内容的.bat文件:
Powershell.exe -File C:\path\to\my\script\myscript.ps1
显然相应地更正了路径。请注意,以这种方式 运行ning 脚本没有任何优势,但您可能使用 .bat 文件的一个原因是,如果您需要更改执行策略以允许脚本执行(我认为您不会在您的case)如下:
Powershell.exe -executionpolicy unrestricted -File C:\path\to\my\script\myscript.ps1
我尝试使用 this post 的代码。
当我直接在 PowerShell 终端上使用此代码时,它 运行 正确。
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
但是当我 运行 .bat 文件上的代码时,cmd window 出现并在几秒钟内消失并且没有进一步的操作。
如果我运行 CMD 上的.bat 文件,出现这个错误:
enter image description here
.bat文件中插入的代码为:
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()
如果你能帮我解决这个问题,我将不胜感激。
谢谢。
您正在尝试 运行 .bat 文件中的 PowerShell 命令(因此没有使用 PowerShell 引擎来执行代码,因此命令失败)。
您需要将脚本保存为 .ps1 文件,然后通过其完整路径名或通过切换到脚本所在的目录并输入:
.\scriptname.ps1
其中 scriptname 是您保存文件的名称。
如果你想通过.bat文件执行脚本,你仍然需要将它保存为.ps1,然后创建一个包含以下内容的.bat文件:
Powershell.exe -File C:\path\to\my\script\myscript.ps1
显然相应地更正了路径。请注意,以这种方式 运行ning 脚本没有任何优势,但您可能使用 .bat 文件的一个原因是,如果您需要更改执行策略以允许脚本执行(我认为您不会在您的case)如下:
Powershell.exe -executionpolicy unrestricted -File C:\path\to\my\script\myscript.ps1