powershell - 在Windows 10上使用Powershell播放视频

标签 powershell windows-10 windows-media-player

我尝试使用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/

相关文章:

c# - 错误找不到类型或命名空间名称 'AxWMPLib'(是否缺少 using 指令或程序集引用?)

powershell - 如何在powershell脚本中填写提示

windows - 在 WSL(Linux 的 Windows 子系统)上挂载磁盘镜像?

windows-10 - 任务计划程序无法启动。附加数据 : Error Value: 2147943726

windows - 视频卡在 Perl 脚本中的 system(1, @commands) 上

javascript - addEventListener 和 wmp 未按预期工作

powershell - 我需要更改一些 "favorites"链接中的 URL

powershell - PowerShell 中的动态参数问题

powershell - 当前的 azure 存储不允许创建新的虚拟机

c# - Office 插件错误 2709 "Offline join completion information was not found"