Link to home
Start Free TrialLog in
Avatar of rakkad
rakkadFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Powershell script running in a dos batch script

Hi

I have created a powershell script that works within powershell, but I need to run the script in command prompt in a dos batch script.  Can anyone help please ?

Thanks
Avatar of Ben Personick (Previously QCubed)
Ben Personick (Previously QCubed)
Flag of United States of America image

Hello Rakkad,

  In your batch file simply put a line in the cmd script calling the PowerShell like this:

CALL Powershell "[Drive\folder\folder\yourscript.ps1"

Open in new window


Usually I like to create a wrapper script file with the same name as the PowerShell script so that I can run it and log the output to a file similar to below:


:: Script Name: PureBackup.cmd
:: Version: 1.1.5
@(
	SETLOCAL
	ECHO OFF
	SET "eLvl=0"
	REM SET "Log=%~dp0log\%~n0_Output.log"
	SET "PS1CMD=%~dpn0.ps1"
	REM SET "_PSDebugLevel=SilentlyContinue"
	SET "_PSDebugLevel=Continue"
)

CALL :Main

(
	ENDLOCAL
	Exit /b %eLvl%
)

:Main

	CALL Powershell %PS1CMD% "%_PSDebugLevel%" >>"%Log%" 2>&1

GOTO :EOF

Open in new window

simply, you can call it within your batch script by adding
powershell -noexit & “C:\script.ps1”

Open in new window


ref:
https://poshoholic.com/2007/09/27/invoking-a-powershell-script-from-cmdexe-or-start-run/
Or you can combine them into one file
@Echo Off
PowerShell.exe -Command "Invoke-Expression -Command ((Get-Content -Path '%~f0' | Select-Object -Skip 3) -join [environment]::NewLine)"
Exit /b %ErrorLevel%
## Powershell starts here
Write-Host "Hello World"

Open in new window

Avatar of rakkad

ASKER

How can I run powershell as an administrator in a dos batch command ?

Thanks
You can't - that would circumvent any measures introduced to not allow exactly for that. We can check if the batch script runs as admin though:
whoami /groups | find "S-1-16-12288" >nul ||  (echo *** Not running elevated - STOP *** & pause & exit /b 1)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ben Personick (Previously QCubed)
Ben Personick (Previously QCubed)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
"You can't" - because you do not use UAC with less than at least confirmation prompt :D.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial