Start a program with argument using Powershell to get administrator privilege - powershell

I have a .bat file like this. But I can not run the SeqEdit.exe as administrator by this command. I research about Powershell but I don't know how to use it correctly. please help me to convert this command to powershell command format.
Thank you in advance.
#echo off
cd "C:\Program Files\National Instruments\TestStand 2016\Bin"
start /min "" SeqEdit.exe /runEntryPoint "Test UUTs" "C:\Peritec\111 Renesas for Oita\SLT Test System_ver109c\Sequence\SLT Test_Main_Ver2016.2.seq"
exit

You can use this:
Set-Location "C:\Program Files\National Instruments\TestStand 2016\Bin"
Start-Process -FilePath ".\SeqEdit.exe" -ArgumentList "/runEntryPoint 'Test UUTs' 'C:\Peritec\111 Renesas for Oita\SLT Test System_ver109c\Sequence\SLT Test_Main_Ver2016.2.seq'" -Verb RunAs -WindowStyle minimized
If you want to do it with cmd first create this batch file:
#echo off
echo Set objShell = CreateObject("Shell.Application") > %temp%\sudo.tmp.vbs
echo args = Right("%*", (Len("%*") - Len("%1"))) >> %temp%\sudo.tmp.vbs
echo objShell.ShellExecute "%1", args, "", "runas" >> %temp%\sudo.tmp.vbs
cscript //nologo %temp%\sudo.tmp.vbs
Now run this from another batch file:
pushd "The location of seqedit.exe"
TheFullPathAndNameOfAboveBatchFile seqedit.exe "arguments" "arguments"

Related

Batch knowing its invoker: cmd.exe or powershell?

I wonder how to check if a batch file is executed by cmd.exe or instead by powershell
I discovered that the ENV variable %CmdCmdLine%is set to something in cmd.exe and should not be set inside a powershell shell.
But if I run a batch file in powershell it temporary assumes a value like C:\WINDOWS\system32\cmd.exe /c ""C:\path\to\check-interpreter.bat""
Given also the inability of batch to check IF PATTERN I cannot find a way to let my batch file be able to know which command interpreter is running.
In the below code I tried to use findstr /R to check cmd at the start of the line. Infact inside cmd.exe the line should start with cmd.exe ... while in powershell should start with the full path C:\WINDOWS\system32\cmd.exe /c ...
Here my attempt:
#ECHO OFF
FOR /F "tokens=* USEBACKQ" %%F IN (`echo %CmdCmdLine% ^^^| findstr /R
"^cmd"`) DO (
SET var=%%F
)
ECHO var set to: %var%
REM IF [%var%]==[] ECHO var set to: %var%
IF DEFINED var (
ECHO CmdCmdLine founnd!
ECHO VAR : %var%
ECHO COMMANDLINE: %CmdCmdLine%
) ELSE (
ECHO CmdCmdLine NOT found..
)
The problem in the above code is that var is not populated at all:
# cmd.exe
C:\path\to>.\check-interpreter.bat
CmdCmdLine founnd!
COMMANDLINE: "C:\WINDOWS\system32\cmd.exe"
# powershell
PS C:\path\to> .\check-interpreter.bat
CmdCmdLine founnd!
COMMANDLINE: C:\WINDOWS\system32\cmd.exe /c ""C:\path\to\check-
interpreter.bat""

Use PowerShell variables in cmd command not working

I am having difficulty with executing a command line in cmd from Powershell. The problem is I can't seem to use my global variables in the command line when cmd is opened from Poweshell. Below is the code I am working with but to no avail. Can someone please provide guidance on this issue?
Start-Process -FilePath "C:\Windows\System32\cmd.exe" -verb RunAs -ArgumentList {/k set Name="$cmdname" set Item="$cmditem" setlocal EnableDelayedExpansion echo "%Name%" }
Thanks,
Roger
The syntax is awkward for sure:
Start-Process -FilePath "C:\Windows\System32\cmd.exe" -ArgumentList "/k set Name=$cmdname & set Item=$cmditem & call echo %name%"
Some of the reasoning here is:
cmd: additional commands need to be separated by &
cmd: the set command takes everything after = until special characters like &
cmd: setlocal EnableDelayedExpansion doesn't really apply here. Use call to delay instead.
delayed variable syntax is also !var! rather than %var%
Powershell: using brackets in -ArgumentList {stuff} sends as a literal string, and variables aren't expanded

Multiple inputs into new prompt & Powershell -run as and -nonewwindow issue

Here is what I currently do, file 1:
powershell.exe -command "Start-Process cmd -ArgumentList '/c cd C:\ && DiskZero.cmd'-Verb runas"
And file 2 "DiskZero.cmd":
#echo off
(echo rescan
echo sel disk 1
echo cle all
echo cre part prim
echo for fs=ntfs quick label=Intenso
echo assign letter=E
) | diskpart
pause
It works as intended, however, there is two files, what I want to do is make it so there's only one file.
I can't manage to find how to input multiple lines of code into a new elevated command prompt with only one script, so instead I'm trying to do it with powershell:
start cmd -nonewwindow works
start cmd -ver runas works
however start cmd -nonewwindow -ver runas doesn't work
What I was hoping to do was this in powershell:
start cmd -nonewwindow -ver runas
#echo off
(echo rescan
echo sel disk 1
echo cle all
echo cre part prim
echo for fs=ntfs quick label=Intenso
echo assign letter=E
) | diskpart
pause
Can anyone help me solve the start cmd -nonewwindow -ver runas issue OR input multiple lines of code into a new elevated command prompt with only one file, please?
Can anyone help me solve the start cmd -nonewwindow -verb runas issue
Unfortunately, there is no solution: Windows fundamentally does not allow you to run an elevated process (run as admin, requested with -Verb RunAs) directly in a non-elevated process' console window - that is why Start-Process syntactically prevents combining -NoNewWindow with -Verb RunAs.
OR input multiple lines of code into a new elevated command prompt with only one file, please?
While there is a solution, it'll be hard to maintain:
You can pass the lines of your second batch file (the one you want to eliminate) to cmd /c on a single line, joined with &:
Note: To facilitate side effect-free experimentation, the original diskpart command was replaced with findstr -n ., which merely prints the lines received via stdin, preceded by their line number.
powershell.exe -command "Start-Process -Verb RunAs cmd '/c cd C:\ && (echo rescan&echo sel disk 1&echo cle all&echo cre part prim&echo for fs=ntfs quick label=Intenso&echo assign letter=E) | findstr -n .&pause'"
That no space char. precedes each & is deliberate, because trailing whitespace in echo commands is significant, i.e. it becomes part of the output; however, it should be fine to place a space char. after each & (as well as before, if the preceding command ignores trailing whitespace).
A better solution is to create a temporary helper batch file from your batch file, pass its path to the PowerShell command, and delete it afterwards:
#echo off
:: Determine the path for a temporary batch file...
:: Note: %~snx0 uses the short (8.3) name of the batch file, so as
:: to ensure that the temp. file path has no spaces, which
:: obviates the need for complex double-quoting later.
set "tmpBatchFile=%TEMP%\~%~snx0"
:: ... and fill it with the desired commands.
:: Note how metacharacters - ( ) | ... - must be ^-escaped.
(
echo #echo off
echo ^(echo rescan
echo echo sel disk 1
echo echo cle all
echo echo cre part prim
echo echo for fs=ntfs quick label=Intenso
echo echo assign letter=E
echo ^) ^| findstr -n .
echo pause
) > "%tmpBatchFile%"
:: Now you can let the elevated cmd.exe process that PowerShell launches
:: execute the temp. batch file.
:: Note: -Wait ensures that the PowerShell call blocks until the elevated
:: cmd.exe window closes.
powershell.exe -command "Start-Process -Wait -Verb RunAs cmd '/c cd C:\ & %tmpBatchFile%'"
:: Delete the temp. batch file.
:: Note: If you do NOT use -Wait above, you'll have to defer deleting
:: the batch file until after the elevated cmd.exe window closes,
:: which you'll have to do manually.
del "%tmpBatchFile%"

How to run .cmd file commands hidden so that they don't show when they run

I currently have a .cmd file that runs the following two commands on startup
PowerShell -Command "Set-ExecutionPolicy Unrestricted" >> "%TEMP%\StartupLog.txt" 2>&1
PowerShell C:\Users\elias\Desktop\Script123.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
But when this runs on startup it shows the command prompt. I'm wondering if there's anyway to run this without showing the command prompt.
Thank You
Invoking a .cmd file directly invariably opens a console window, so you need to invoke it via a wrapper executable that hides it:
This answer of mine contains a VBScript script that does just that; assuming you've saved it as runHidden.vbs in the current dir and that you want to invoke some-batch-file.cmd from the current dir:
wscript .\runHidden.vbs cmd "/c .\some-batch-file.cmd"
Try powershell -command "& { $x = New-Object -ComObject Shell.Application; $x.minimizeall() }" in the beginning of the code.
This command can minimize all windows.
I hope this can be helpful, if you have any other questions, please comment below.
Create a wrapper with VBScript:
Option Explicit
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "cmd /c blah.cmd", 0, False
Then change the startup item to
wscript.exe wrapper.vbs

Powershell: running JScript scripts without logo

I set cscript.exe as my default scripting host with the nologo option. Therefore in cmd.exe
I get, as expected:
> ftype jsfile
jsfile="C:\Windows\System32\CScript.exe" //nologo "%1" %*
> reg query HKCR\jsfile\Shell\Open\Command
HKEY_CLASSES_ROOT\jsfile\Shell\Open\Command
(Default) REG_EXPAND_SZ "C:\Windows\System32\CScript.exe" //nologo "%1" %*
> echo WScript.Echo("Test Echo"); > test.js
> test.js
Test Echo
But, moving to Powershell:
> powershell -nologo
PS > .\test.js
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
Test Echo
It seems that CScript does not get //nologo from Powershell shell.
How can I fix this?
More use cases
It also works with:
PS > cscript.exe //nologo test.js
Test Echo
PS > cmd /c test.js
Test Echo
PS > cmd /c test
Test Echo
Copy & Paste Test
Someone suggests it can be a bug. To check if it applies to you, you can copy the following in a PS console with elevated privileges:
## Change the host to cscript nologo and store old setting
$jstype="Registry::HKEY_CLASSES_ROOT\jsfile\Shell\Open\Command"
$jsvalue=("`"$env:SystemRoot\System32\CScript.exe`"" + ' //nologo "%1" %*')
$old=(gp -Path $jstype )."(default)"
Set-Item -Path $jstype -value $jsvalue
## The output should be the same (i.e. nologo!)
echo 'WScript.Echo("Test Echo");' > test.js
cmd /c test
.\test.js
## Restore old settings
Set-Item -Path $jstype -value $old
Is cmd /c test and .\test.js output the same?
Details on the problem
It seems that Powershell has a weird behaviour with respect to file associations.
If you paste the following snippet in an elevated privilege PS shell:
$jstype="Registry::HKEY_CLASSES_ROOT\jsfile\Shell\Open\Command"
Set-Item -Path $jstype -value "cscript.exe total non sense"
echo 'WScript.Echo("Test Echo");' > test.js
cmd /c test.js
... you get the deserved error for associating jsfiles with the command string cscript.exe total non sense.
But surprisingly writing:
.\test.js
works like a charm. So it seems that PS only reads the first item of the open-command-string (here cscript.exe) and then appends to it the user string (.\test.js), totally disregarding the other elements of the open-string, here total non sense.
To confirm paste this:
Set-Item -Path $jstype -value "notepad.exe total non sense"
echo 'WScript.Echo("Test Echo");' > test.js
cmd /c test.js
cmd.exe opens the Notepad which proposes to create the file "total non sense.txt".
Now write:
.\test.js
Based on what I just said, the actual command run will be notepad.exe .\test.js and in fact the Notepad will now open .\test.js.
Solution
Whether or not this is a bug, a possible solution is to create a batch script calling the cscript.exe with the desired parameters. I will name it C:\Windows\System32\cscript.cmd.
To create the script and the related association, paste:
echo "#cscript.exe //nologo %*" | out-file -encoding ASCII C:\Windows\System32\cscript.cmd
$jstype="Registry::HKEY_CLASSES_ROOT\jsfile\Shell\Open\Command"
$jsvalue=("`"$env:SystemRoot\System32\cscript.cmd`"" + ' "%1" %*')
Set-Item -Path $jstype -value $jsvalue
As you see //nologo is moved from the registry to cscript.cmd.
Note that echo "string" > would produce a Unicode file, which cmd.exe dislikes, hence the ASCII filter.
Print your new .js opening command:
cmd /c ftype jsfile
That is: jsfile="C:\Windows\System32\cscript.cmd" "%1" %*.
Now both:
cmd /c test
.\test
will produce:
Test Echo
without the banner, and note that in both cases you don't need to specify the .js extension.
For simplicity I set cscript.cmd to run cscript.exe straight. You might want to specify its full path.