如何在没有辅助文件的情况下通过批处理文件运行Powershell脚本

时间:2016-05-27 15:21:18

标签: windows powershell batch-file cmd ps1

我有两个文件,一个名为Startmenu.bat,第二个名为test.ps1

Startmenu.bat:

@echo ON
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "C:\test.ps1"' -Verb RunAs}";

test.ps1:

Get-AppXPackage -AllUsers | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppXManifest.xml"}

如果我运行Startmenu.bat并将test.ps1放置到C:\

,这两个文件就能正常运行

但是我的问题是否可以只创建一个文件?我可以以某种方式在第一个文件中包含Powershell脚本,我的意思是Startmenu.bat?我想制作一个文件,我真的不知道如何。

Windows 10中的“我的开始”菜单已损坏,我必须运行Powershell命令才能访问“开始”菜单(每次启动时)。

1 个答案:

答案 0 :(得分:1)

答案就在于问题!您首先使用-Command参数运行PowerShell,该参数直接运行PowerShell命令;碰巧你正在使用它再次打开PowerShell(使用RunAs动词使其升高)。您只需再次使用-Command,而不是使用-File

另一种方法是使用-EncodedCommand参数和Base64编码PowerShell命令。

运行powershell.exe -help

时,请参阅帮助的最后部分
# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand