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/
此解决方案类似于walid2mi(感谢您的灵感),但允许通过Read-Host cmdlet输入标准控制台.
优点:
缺点:
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)
未经测试的.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)
归档时间: |
|
查看次数: |
141262 次 |
最近记录: |