Using a cmd command in powershell script? - windows

I am trying to make a powershell script that automatically sets up this program and requires to use a cmd command to run do it.
I know that the cmd command work and I tried cmd.exe.
cmd.exe /c "java -jar fitnesse-standalone.jar -p 9090"
Error Message:
cmd.exe : The term 'cmd.exe' is not recognized

You can use start-process
Start-Process -FilePath "cmd.exe" -ArgumentList '/c "java -jar fitnesse-standalone.jar -p 9090"'
The /c and everything following it is just part of the one set of parameters being passed to cmd. If you want powershell to wait for the the Java app to close, add the -wait parameter.
There's also no real need to use CMD at all in this case (since your giving it /c to exit immediately anyway), you can call java directly:
Start-Process -FilePath "java.exe" -ArgumentList '-jar fitnesse-standalone.jar -p 9090'
and it should be the same.
Note: you'll need Java in your path or the current working directory, and fitnesse-standalone.jar in the current directory for either of these to work.

Related

Writing a powershell script to re-start itself

I'm trying to make a powershell script restart itself in the event of failure. Following on from a couple of references I've found here and here I've added this line...
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file "$PSCommandPath"'
($PSCommandPath is the path and filename of the script)
What happens when my script gets to this point is that a window flashes up for a fraction of a second and then closes.
I think (but can't be sure) that the window that appears is a powershell console - it disappears too quickly to read.
The first questions is why isn't the -noexit parameter working - it should make the window of the new process remain open even if there's an error.
The 2nd question is how to get it to work, I've tried various combinations of the command including....
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file c:\my_dir\my_script.ps1 '
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file $PSCommandPath'
Invoke-Expression -Command 'cmd /c start powershell.exe -NoExit -file "$PSCommandPath"'
The only version that does work (almost) is....
Invoke-Expression -Command ($PSCommandPath)
which does restart the script, but it doesn't do it in a new window it re-starts in the existing window (not what I'm looking for). The script has read and execute permissions (all users). This is a particularly frustrating problem in that I'm pretty sure this was working in the past, so it may be system problem rather than a script problem.
Update - I used Invoke-Expressions because that's what the examples I found used (and at the time I'm sure I got it to work!)
This solutions does work....
Start-Process -FilePath "$PSHOME\powershell.exe" -ArgumentList '-NoExit', '-File', """$PSCommandPath"""
Thanks
No need to search so far...
. $PSCommandPath
Note the space between the dot and $PSCommandPath.

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)

call bat file in new windows from powershell

I want to launch a bat file in new window/independent instance from within powershell.
the bat file will take a computername from powershell
e.g.
mybat.bat $thiscomputer
Ive tried
start mybat.bat $thiscomputer
start "cmd /c" mybat.bat $thiscomputer
start /k mybat.bat $thiscomputer
start-process mybat.bat $thiscomputer
ordinarily the bat does run but stays within the powershell script.
I need the powershell script to launch the bat in anew window and loop back to the beginning.
Thanks
Confuseis
Start-Process runs console programs in a new window by default. The only problem with your syntax is that you need to use the -ArgumentList parameter to pass arguments to the program you've started. PowerShell doesn't let you simply list them after the program name.
PS> Start-Process $env:comspec -ArgumentList "mybat.bat $thiscomputer"
or, in shorter form,
PS> start mybat.bat -a $thiscomputer
-ArgumentList only takes one string, so if you have multiple arguments to pass, then you need to put them all into one string before passing to Start-Process.

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.

Unable to execute multi-command in power shell

I'm working on power shell script using windows 2012 server, that do simple two functions
open powershell as an administrator
change the directory to c:\user\scrpt.bat
the code is:
powershell -Command "& {powershell Start-Process PowerShell -Verb RunAs; Set-Location C:\}
the problem is not when execute the first part, it's in the other part which is:
Set-Location C:\}
My question is there any way after running powershell as administrator execute the next command ?
I already tried to use semicolon ";" but no luck
If you want to change directory for the process you're spawning - use -WorkingDirectory option:
powershell -Command "& { Start-Process PowerShell -Verb RunAs -WorkingDirectory 'D:' }"

Resources