How to have powershell script execute batch command in same terminal - windows

I have a powershell 2 script that I'm trying to develop. The purpose of this script is to wrap around a batch script and intelligently choose what version of said batch script to run. Somewhere along the lines in my code I have some logic that goes like this:
& $myCommand $args
$myCommand is the fully qualified filename of the batch file I want to run. $args is the args passed into this script. This works except it opens up a command window when running $myCommand. How do I prevent this so that the output is within the same powershell shell?
What's odd is that if I execute the command directly, it shows up the way I want it. So something like:
C:\myCommand.bat $args
Given that I need to choose which command I want to run at runtime, how do I make it so the output is in the same shell when I use the '&' to execute the command in the variable? Thanks!

Use Start-Process with the -NoNewWindow parameter instead of &:
Start-Process -filepath C:\myCommand.bat -argumentList #("arg1","arg2") -NoNewWindow

Related

Open a command file with Windows PowerShell running it directly

I want to make a file having Windows Powershell commands. Then I want to open it with windows powershell directly and without pressing any key I want windows powershell start running those commands directly same as command prompy I can make .cmd or .bat file.
For example:
These are two commands or Powershell, I want to save this file. Then I want directly execute this file by powershell. I have tried to save it as ps1 and ps2 extension as well but not working. Many methods online are not working. Any solution?
PowerShell script files, across all versions, use the .ps1 filename extension.
From within PowerShell, you can invoke them directly, e.g., .\script.ps1
Note that, unlike in cmd.exe, you must use .\ (or a full path) in order to execute a file located in the current directory - just script.ps1 won't work - see this answer for background information.
From cmd.exe, you must use PowerShell's CLI (powershell.exe in Windows PowerShell / pwsh in PowerShell [Core] v6+) in order to execute a script file:
powershell.exe -File script.ps1
pwsh -File script.ps1 (-File may be omitted)
Note that with -File the .\-prefix is not required.
However, if you use -Command (-c) instead (which is the default with powershell.exe, whereas pwsh now defaults to -File), you do need the .\, because the -Command argument(s) are interpreted as a piece of PowerShell code, i.e. as if you had submitted it inside a PowerShell session.
You've discovered this in your own answer, where you pass a PowerShell command directly to the (implied) -Command parameter.
Note, however, that it's better to double-quote such commands, so as to prevent cmd.exe from interpreting certain characters itself, which breaks the call.
For instance, the following call would break, if you didn't enclose the -Command (-c) argument in "...":
# From cmd.exe; "..." required.
C:\>powershell.exe -c "Write-Output 'a & b'"
a & b
Another important consideration is that you need to escape embedded " chars. as \" for the CLI (even though PowerShell-internally you would use `" or ""):
# From cmd.exe; note the inner " escaped as \"
C:\>powershell.exe -c "Write-Output \"hi there\""
hi there
I have found the solution. I use command powershell.exe and can directly execute powershell commands within cmd.
powershell.exe $MyVariable=Get-Content .\Path.txt
is working fine for me

What is the PowerShell equivalent of bash's exec()?

Newbie to PowerShell here. What's the best way to run a new script from within the current process without creating a subshell? In Bash, you would do this via:
source script # Executes the commands in script within the current shell
or
exec script # Same as source, except it completely replaces the current process with script
Is there an equivalent for this in PowerShell?
You can also use .\Script.ps1
Or start typing the name and use TAB to complete the script name.
Dot-sourcing a script allows a function to become available on the command line.
For example:
Function Get-LocalTime {
$CurTime = Get-Date
"The Date and time currently is $CurTime"
}
Now we dot source (name the above script Example.ps1) PS C:\>. .\Example.ps1
Allowing us to simply type and Tab complete Get-LocalTime
-edit to comment, you can define a function and use the function immediately in the same script. So in Example.ps1, at the last line just enter Get-LocalTime

VB6: Execute two command via Shell

I'm trying to execute two command via vb6 Shell command. two command have been splited with " && " string. here is what I want to execute:
"D:\thepath\unzip.exe" -o -q "D:\7zipa.zip" -d"D:\7zipa_zip" && cmd /c echo Hi>C:\Users\AmirrezA\AppData\Local\Temp\UZP.txt
When second command comes to execute, It have been known as a part of "D:\thepath\unzip.exe" but when I'm trying to execute the same line above via windows Command Prompt, there is no problem. What is wrong with the line above that can not be executed via VB6 shell function?
The VB6 Shell() function is a thin wrapper on CreateProcess() and doesn't involve a "shell" at all. CreateProcess() does not understand the command syntax of CMD.EXE and operates at a far lower level.
To do what you seem to think you want you have to use Shell() to run an instance of "fat old CMD.EXE" (command shell) and pass your commands to that.

Launch PowerShell from Command Prompt with custom prompt

I'm trying to open PowerShell with a customised prompt (for instance the UNIX shell prompt). I have tried:
powershell -noexit -command "& {function prompt {"$(pwd)$ "}}"
But it just starts powershell without the prompt I want. It does actually work in powershell itself. Could I get this to work or do I have to make a seperate file and do it through "-file"?
Not sure what the UNIX prompt defaults too but this should do what I think you want it to do.
powershell -noexit -command "function prompt {'{0}$ ' -f $pwd}"
If you use single quotes in the prompt function the $ doesn't get interpolated, and you don't have to worry about to many quotes.
SAVING THE PROMPT FUNCTION
Like any function, the Prompt function exists only in the current
session. To save the Prompt function for future sessions, add it to your
Windows PowerShell profiles. For more information about profiles,
see about_Profiles.
Here's how to create a new profile:
if (!(test-path $profile))
{new-item -type file -path $profile -force}
notepad $profile
Quoting on the command-line is tricky. Also, & runs a scriptblock in its own scope, so functions defined there don't "leak" out to the calling scope. The dot operator (also called dot-sourcing) is what you're looking for. This is what I got to work using backslashes to quote the strings.
powershell -noexit -command ". {function prompt {\"$(pwd)$ \"}}"
Add your custom prompt to your profile and it will load/run every time you start PowerShell.
Powershell customisation is always a bit tricky. Try adding a script with a method called prompt() like this:
function prompt() {
$myPrompt = "Ready>";
write-host -NoNewLine -ForegroundColor green $myPrompt
' '
}
Then call this in a profile, such as the one for all users:
%windir%\system32\Windows­PowerShell\v1.0\profile.ps1
Good luck!

How to propagate windows environment variable for powershell run from cygwin

I have installed cygwin and I am about to execute a script written in powershell. I do it like this:
powershell "& ""C:\my\script.ps1"""
This works as expected, I have to do this that way because in that script I am executing another external command and so on ...
I would like to add some environment variable to that script, so I would like to write something like
powershell "$FOO="bar"; & ""C:\my\script.ps1"""
so I can then access $FOO variable in the script and do something with it. The idea is that if that variable is not defined, I use some default value. I know that this could be also achieved with some environment variables or I could put these variables to the profile (profile.ps1) but I want to get rid of that file so I need none and I can override the default value with the variables as I showed.
but is says that:
=bar : The term '=bar' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
So I was thinking that something like this could work:
powershell { $web = "google.com" ; & ping.exe $web }
But it works only in powershell console and not in cygwin, it cygwin it says that
-bash: syntax error near unexpected token `&'
So it seems like that & is treaten as bash character. I tried to escape it in thousand ways, e.g.
bash -c "'powershell { \$web = \"google.com\" ; & ping.exe \$web }'"
But this is the output
bash: powershell { $web = "google.com" ; & ping.exe $web }: command not found
Thank you for a hint.
UPDATE
I am able to do this:
powershell "Invoke-Command -ScriptBlock {\$env:FOO = \"google.com\" ; & ""C:\my\script.ps1"" }"
But when I am trying to access that FOO variable throught $env:FOO it is empty, it seems like I am unable to do so because that script is running in another scope or what ...
this command will pass an environment variable from cygwin ($FOO="bar") to powershell, then run another powershell command (dir env:) which lists the environment variables (proving that it was set):
powershell "\$env:FOO=\"bar\";dir env:"
replace the dir env: part with your script call and this should work for you.
edit: here's the command (quoted slightly differently) including the call to an external script:
powershell '$env:FOO="bar";& "C:\script name.ps1"'

Resources