How to pass variable from Batch File to a Powershell Script - windows

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.

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

Keep batch script running after launching powershell within

I am using a batch script to automate a lot of tasks I have to run on a computer.
In the batch file I have a menu making you choose between each task separately or do everything.
When I choose to do everything, after launching the first .ps1 it just kills my cmd window.
I found some way to keep the window open but the script doesn't continue...
Also I created a "master file" to call all the ".ps1" and tried those cmds: call, /wait
The call feature works and they all start. So I don't understand why they would do the same in my script.
The cmd lines bellow are not bellow each other in my script because I want to be able to call them separately.
Part of the script I would like to run properly:
echo Windows Layout
start /wait PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0Customisation\Export_Import_Layout.ps1""' -Verb RunAs}"
echo Remove Unwanted Apps
start /wait PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0Clean\RemoveAppx.ps1""' -Verb RunAs}"
wmic product where name="WinZip 22.5" call uninstall
ping -n 6 localhost >nul
Taskkill /IM /F "MicrosoftEdge.exe"
Taskkill /IM /F "MicrosoftEdgeCP.exe"
Taskkill /IM /F "MicrosoftEdgeSH.exe"
%~dp0Clean\MCPR.exe
The master.bat looks like this :
call PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0InstallChocoAndApps.ps1""' -Verb RunAs}"
call PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dp0Clean\RemoveAppx.ps1""' -Verb RunAs}"
Any hint would be appriciated.
Please keep in mind I am not a script specialist.
Thanks
Ben
Managed to solve my issue by adding start "" /wait instead of start /wait

How to start PowerShell script from BAT file with proper Working Directory?

I'm trying to create bat script that can start PowerShell script named the same as bat file in proper working directotry.
This is what I got:
#ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -WorkingDirectory '%~dp0' -Verb RunAs}"
PAUSE
Passing working directory this way does not work.
How to make script that will pass proper working directroy and also command line arguments?
The -WorkingDirectory parameter doesn't work when using -Verb RunAs. Instead, you have to set the working directory by calling cd within a -Command string.
This is what I use: (cmd/batch-file command)
powershell -command " Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%cd%'; & 'PathToPS1File';`\""\"" "
If you want to make a "Run script as admin" right-click command in Windows Explorer, create a new registry key at HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\Run with PowerShell (Admin)\Command, and set its value to the command above -- except replacing %cd% with %W, and PathToPS1File with %1 (if you want it to execute the right-clicked file).
Result: (Windows Explorer context-menu shell command)
powershell -command " Start-Process PowerShell -Verb RunAs \""-Command `\""cd '%W'; & '%1';`\""\"" "
EDIT: There's an alternative way to have the script be run as admin from Explorer, by using the "runas" sub-key: https://winaero.com/blog/run-as-administrator-context-menu-for-power-shell-ps1-files
If you want to run your script as admin from an existing powershell, remove the outer powershell call, replace %W with $pwd, replace %1 with the ps1 file-path, and replace each \"" with just ".
Note: The \""'s are just escaped quotes, for when calling from the Windows shell/command-line (it's quote-handling is terrible). In this particular case, just \" should also work, but I use the more robust \"" for easier extension.
See here for more info: https://stackoverflow.com/a/31413730/2441655
Result: (PowerShell command)
Start-Process PowerShell -Verb RunAs "-Command `"cd '$pwd'; & 'PathToPS1File';`""
Important note: The commands above are assuming that your computer has already been configured to allow script execution. If that's not the case, you may need to add -ExecutionPolicy Bypass to your powershell flags. (you may also want -NoProfile to avoid running profile scripts)
A workaround is to let the PowerShell script change the directory to it's own origin with:
Set-Location (Split-Path $MyInvocation.MyCommand.Path)
as the first command.
As per mklement0s hint: In PSv3+ use the simpler:
Set-Location -LiteralPath $PSScriptRoot
Or use this directory to open adjacent files.
$MyDir = Split-Path $MyInvocation.MyCommand.Path
$Content = Get-Content (Join-Path $MyDir OtherFile.txt)

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.

Wrapping a PowerShell Program in a Batch File and Using "Set-Location" Returns Root

The following code worked perfectly-
$ScriptLocation = Get-Location
Set-Location "$ScriptLocation"
...until I created a batch file to kick the script off. I understand that by opening the script via the batch file the location will be the root directory.
My question is, how can I set the current directory to the directory where the script is when launching the script from a batch file?
My batch file has the following code-
#ECHO OFF
SET ScriptDirectory=%~dp0
SET ScriptPath=%ScriptDirectory%FilePush_V0.1.ps1
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""%ScriptPath%""' -Verb RunAs}";
set-Location $PSScriptRoot
cd..
See the following for your version of powershell.
whats-the-best-way-to-determine-the-location-of-the-current-powershell-script

Resources