¿Cómo ejecutar comandos de powershell desde un archivo por lotes?


Tengo un script de PowerShell para agregar un sitio web a Sitios de confianza en 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

Quiero ejecutar estos comandos de PowerShell desde un archivo por lotes. Parece simple cuando tengo que ejecutar un solo comando, PERO en este caso tengo una secuencia de comandos relacionados. Quiero evitar crear un archivo separado para que el script PS sea llamado desde el lote - todo debe estar en el archivo por lotes.

La pregunta es: Cómo ejecutar comandos de powershell (o declaraciones) de un archivo por lotes?

Author: SteveC, 2011-05-18

5 answers

Así es como se vería el código en un archivo por lotes (probado, funciona):

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;}"

Basado en la información de:

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

 55
Author: Hassan Voyeau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-18 20:37:43

Escriba cmd.exe Powershell -Help y ver los ejemplos.

 7
Author: Emiliano Poggi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-17 21:58:33

Esta solución es similar a walid2mi (gracias por su inspiración), pero permite la entrada de consola estándar del cmdlet Read-Host.

Ventajas:

  • se puede ejecutar como estándar .cmd file
  • solo un archivo para batch y script de powershell
  • el script de powershell puede ser multilínea (script fácil de leer)
  • permite la entrada de consola estándar (use el cmdlet Read-Host de forma estándar)

Contras:

  • requiere powershell versión 2.0 +

Ejemplo comentado y ejecutable de 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 .

Fragmento para .archivo 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...
 3
Author: kapitanrum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-01 18:27:40

No probado.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
 1
Author: walid2mi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-20 19:12:19

Buscando la posibilidad de poner un script de powershell en un archivo por lotes, encontré este hilo. La idea de walid2mi no funcionó al 100% para mi guión. Pero a través de un archivo temporal, que contiene el script que funcionó. Aquí está el esqueleto del archivo por lotes:

;@echo off
;setlocal ENABLEEXTENSIONS
;rem make from X.bat a X.ps1 by removing all lines starting with ';' 
;Findstr -rbv "^[;]" %0 > %~dpn0.ps1 
;powershell -ExecutionPolicy Unrestricted -File %~dpn0.ps1 %*
;del %~dpn0.ps1
;endlocal
;goto :EOF
;rem Here start your power shell script.
param(
    ,[switch]$help
)
 0
Author: eremmel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-07 11:02:44