如何从批处理文件中执行powershell命令?

And*_*rei 45 powershell command-line batch-file powershell-2.0

我有一个PowerShell脚本将网站添加到Internet Explorer中的可信站点:

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item TESTSERVERNAME
set-location TESTSERVERNAME
new-itemproperty . -Name http -Value 2 -Type DWORD
Run Code Online (Sandbox Code Playgroud)

我想从批处理文件中执行这些PowerShell命令.当我必须运行单个命令时似乎很简单,在这种情况下,我有一系列相关的命令.我想避免为批处理调用PS脚本创建单独的文件 - 所有内容都必须在批处理文件中.

问题是:如何从批处理文件中执行powershell命令(或语句)?

Has*_*eau 68

这是批处理文件中的代码(测试,工作):

powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"
Run Code Online (Sandbox Code Playgroud)

根据以下信息:

http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

  • 我如何分割长线?与你的例子类似的行. (3认同)

Emi*_*ggi 9

键入cmd.exe Powershell -Help并查看示例.


kap*_*rum 6

此解决方案类似于walid2mi(感谢您的灵感),但允许通过Read-Host cmdlet输入标准控制台.

优点:

  • 可以像标准的.cmd文件一样运行
  • 批处理和PowerShell脚本只有一个文件
  • powershell脚本可能是多行的(易于阅读的脚本)
  • 允许标准控制台输入(通过标准方式使用Read-Host cmdlet)

缺点:

  • 需要PowerShell版本2.0+

batch-ps-script.cmd的注释和可运行示例:

<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script

# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"

# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
    Write-Host "Exit script..."
    break
}

# example: call standard powershell command
Get-Item .
Run Code Online (Sandbox Code Playgroud)

.cmd文件的摘录:

<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...
Run Code Online (Sandbox Code Playgroud)


wal*_*2mi 5

未经测试的.cmd

;@echo off
;Findstr -rbv ; %0 | powershell -c - 
;goto:sCode

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item TESTSERVERNAME
set-location TESTSERVERNAME
new-itemproperty . -Name http -Value 2 -Type DWORD

;:sCode 
;echo done
;pause & goto :eof
Run Code Online (Sandbox Code Playgroud)