我尝试使用this发布的代码。
当我直接在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窗口会出现,并在几秒钟内消失,并且无需进一步操作。
如果我在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
显然要相应地纠正路径。请注意,以这种方式运行脚本没有任何好处,但是您可能使用.bat文件的一个原因是,如果需要更改执行策略以允许脚本执行(我不认为您这样做),如下所示:
Powershell.exe -executionpolicy unrestricted -File C:\path\to\my\script\myscript.ps1
关于powershell - 在Windows 10上使用Powershell播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42495060/