powershell command output logging in batch script - windows

I need to write this command to a bat file in a specific location:
echo PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "C:\Users\ADMINI~1\AppData\Local\Temp\2\StartupLog.txt" >> c:\myscript.bat
When I run this command it will only write PowerShell -Command "Set-ExecutionPolicy Unrestricted in myscript.bat.
I need to write the full command with the output file logging. Is this possible to do this?
Thanks!

Read Syntax : Escape Characters, Delimiters and Quotes and apply it as follows:
echo PowerShell -Command "Set-ExecutionPolicy Unrestricted" ^>^> "C:\Users\ADMINI~1\AppData\Local\Temp\2\StartupLog.txt" >> c:\myscript.bat
Proof (copy & paste from a cmd window, so lines are wrapped):
d:\bat> type myscript.bat
The system cannot find the file specified.
d:\bat> echo PowerShell -Command "Set-ExecutionPolicy Unrestricted" ^>^> "C:\Users\ADMINI~1\
AppData\Local\Temp\2\StartupLog.txt" >> myscript.bat
d:\bat> type myscript.bat
PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "C:\Users\ADMINI~1\AppData\Local\T
emp\2\StartupLog.txt"
d:\bat>

Related

How can I change directory directly from the windows run prompt?

How can I change the current directory from the the windows run prompt when we initialize powershell as powershell. For eg: powershell --someArgs
You can use Set-Location or Cd
Powershell.exe -noexit -Command "CD 'C:\Test\'"
Powershell.exe -noexit -Command "Set-Location 'C:\Test\'"
Launch cmd.exe and use the builtin start command's /d flag to launch powershell.exe with a specific working directory:
cmd /c start /d "C:\working\directory\goes\here" powershell.exe
This will set the working directory of the powershell.exe process to C:\working\directory\goes\here, in turn causing PowerShell's $PWD to change to that directory

close powershell window from batchscript

I want to close powershell window after my batch script completes execution.
This is my batch script. I tried exit command but it is closing only command prompt.
#ECHO OFF
setlocal EnableDelayedExpansion
start PowerShell.exe -Command help
powershell.exe -command exit
I want to close powershell window from my batchscript. Which command I am missing?
Kindly use below code in your CMD prompt to kill the existing PowerShell window.
taskkill /IM "powershell.exe" /F
Multiple commands on the same line are separated by a SEMICOLON ;.
powershell -NoLogo -NoProfile -Command "help; exit"
Does this do what you want?

How to pass variable from Batch File to a Powershell Script

I have a batch file that copies user files from one computer to another networked computer.
#echo off
cls
#echo Type the old Computer Name
set /p asset=
REM robocopy.exe \\%asset%\c$\ C:\ /S /Z /XJD /XJ /XA:SH /XA:T /XD "Dir1" "Dir2" /XF *.dll *.log *.txt *.exe /log+:"\\server\path\%asset%-to-%computername%-Transfer.log" /NP /FP /V /TEE
PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
pause
This is my PowerShell script:
$source = "\\${env:asset}\C$\Temp\Source"
$dest = "C:\Temp\Dest"
Write-Output $source
Read-Host "Press ENTER to quit"
I then need to call a PowerShell script that invokes an admin login, then pass the %asset% and %useraiu% variables.
I can't seem to figure out how to pass the %asset% and %useraiu% from my batch file to the PowerShell script.
I have found that if you are calling the Powershell script from a batch file and need to have the Powershell script run with admin, you would need to use this syntax.
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%~dpn0.ps1"""" """"%asset%"""" ' -Verb RunAs}"
The PowerShell script name and parameters need to be wrapped in 4 double quotes in order to properly handle paths/values with spaces
This is the only solution that worked for me so far.

Not able to capture output by runas command

I have to automate test cases.
Tasks:-
Step:-Open administrative command prompt from powershell.
Step:-Execute a batch file on the administrative command prompt.
Step:-Batch file includes some set of commands, including a execution of an exe.
For Example:- runas /user:administrator /savecred someCmd.exe >>D:\output.txt
Step:-Capture output of the exe in a variable for verification of the output.
i have used "
start-process -verb runas cmd.exe $param" cmdlet for opening administrative command prompt(Step 1).
Where $param contains the batch file to be executed.
Problem Statement:- When batch file executes the runas command mentioned above, it opens a new command prompt and the output is displayed in the prompt and it closes itself.
i am not able to capture the output(not getting written in the output.txt) based on which i have to do some verification.
you can use the the output redirection from the batch :
$params="/C ipconfig /all 2>&1 >>c:\temp\test.txt"
start-process -verb runas cmd.exe $params
gc c:\temp\test.txt
I ended up creating a wrapper batch file OutputWrapper.bat that takes at least two arguments:
1) output file
2) command
3) [optional] arguments
#ECHO OFF
IF "%2" == "" GOTO usage
SET OUTPUTFILE=%1
SET COMMAND=%2
SET ARGS=
SHIFT /2
:loop1
IF "%2"=="" GOTO exec
SET ARGS=%ARGS% %2
SHIFT
GOTO loop1
:exec
ECHO Command [%COMMAND%]
ECHO Arguments [%ARGS%]
ECHO Output file [%OUTPUTFILE%]
%COMMAND%%ARGS% > %OUTPUTFILE% 2>&1
GOTO end
:usage
ECHO Usage: %~nx0 outputfile command [arguments]
:end
and calling it from PowerShell like this:
$outFile = "C:\Temp\Deploy.out";
Start-Process -FilePath .\OutputWrapper.bat -ArgumentList "$outfile","whoami.exe","/priv" -Verb RunAs -Wait
Get-Content $outFile;
Solution
Open administrative command prompt from powershell.
executed a batch file in the runas command. For example: runas /user:administrator /savecred mybatch.bat
Batch file includes some set of commands, including a execution of an exe. For example someCmd.exe >>D:\output.txt
Capture output of the exe in a variable for verification of the output.
Now the output was captured and was written into a file. My target was to capture the output of the command and this was the solution through which I solved it.
I had the same problem and solved it by the use of gsudo. It let me run the elevated command and tunneled the output back from it.
gsudo {command-to-execute}
Improvement on Loïc MICHEL's answer, as without -Wait, it's likely that Get-Content will run before the process has finished. As the output isn't written until the process ends, Get-Content fails as the file does not exist.
$param = "ipconfig /all"
$args = "/C $param 2>&1 > C:\temp\test.txt"
Start-Process -FilePath cmd.exe -ArgumentList $args -Verb RunAs -Wait
Get-Content -Path C:\temp\test.txt
Alternatively, using powershell.exe instead and a random file in the temporary directory for the OS:
$CommandWithParameters = "gpresult /scope computer /z"
$OutputFile = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName())
$Arguments = ("{0} 2>&1 > {1}" -f $CommandWithParameters, $OutputFile)
Start-Process -FilePath powershell.exe -ArgumentList $Arguments -Verb RunAs -Wait
Get-Content -Path $OutputFile
Using powershell.exe will save the output file using UCS-2 LE BOM encoding. If you use cmd.exe, the encoding will be ANSI.

How to run PowerShell in CMD

I'm trying to run a PowerShell script inside cmd command line. Someone gave me an example and it worked:
powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"
But the problem is my PowerShell script has input parameters, so I tried, but it doesn't work:
powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' "
The error is:
The term 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' is not recognized as the name of a cmdlet, function,
How can I fix this problem?
You need to separate the arguments from the file path:
powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"
Another option that may ease the syntax using the File parameter and positional parameters:
powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"
I'd like to add the following to Shay Levy's correct answer:
You can make your life easier if you create a little batch script run.cmd to launch your powershell script:
run.cmd
#echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"
Put it in the same path as SQLExecutor.ps1 and from now on you can run it by simply double-clicking on run.cmd.
Note:
If you require command line arguments inside the run.cmd batch, simply pass them as %1 ... %9 (or use %* to pass all parameters) to the powershell script, i.e.
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*
The variable batchPath contains the executing path of the batch file itself (this is what the expression %~dp0 is used for). So you just put the powershell script in the same path as the calling batch file.
Try just:
powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

Resources