I have a batch file that allows me to go to particular folder based on my input.
d:
cd d:\test\bits
#ECHO off
cls
:start
ECHO.
ECHO 1. Perl
ECHO 2. Python
set choice=
set /p choice=type in number to go to appropriate code folder:
if not '%choice%'=='' set choice=%choice:~0,1%
if '%choice%'=='1' goto pl
if '%choice%'=='2' goto py
ECHO "%choice%" is not valid, try again
ECHO.
goto start
:pl
cd code\pl
goto end
:py
cd code\py
goto end
:end
start "bits"
At the end of execution, a command prompt window with the title "bits" opens up and is in the specified directory corresponding to the input choice. This is all good. But I want to have the same thing done with Powershell.
If, instead of start "bits", I put, start powershell, in the last line, I can get Powershell console to open. By doing this, I have two issues.
Powershell console is still in d:\test\bits folder and not in the one I intended it to go.
I cannot get the title to be bits
How do I get the functionality I want with Powershell?
From what I expected and what I was able to reproduce with your script, the current directory is set to the intended one (d:\test\bits\code\pl if I enter 1)
For the title part, you can do the following:
start powershell -NoExit -command "$Host.UI.RawUI.WindowTitle = 'bits'"
If you add this to your powershell profile.ps1 you can get the window title to show the current running script and if you are just opening a window with no script then 'pwsh' will be displayed.
Will be systematic with no need to add a line on top of each script. The other answers
combined with $MyInvocation.MyCommand seem to give the name of the profile.ps1 instead when running a script from the context menu.
This can also be tweaked to change the result.
[console]::title = Split-Path -Leaf ([Environment]::GetCommandLineArgs()[-1]).Replace('pwsh.dll','pwsh')
Works on both PS 5 and 7 . For ver. 5 replace pwsh.dll by powershell.exe
Related
I have this PowerShell command line which usually opens a webpage via Google Chrome, but I would like that to open randomly with Chrome and Firefox.
start-process -FilePath chrome.exe "www.quora.com"
One PowerShell solution for usage in a PowerShell script or in PowerShell console window is as posted by Santiago Squarzon:
start-process -FilePath ('chrome.exe','firefox.exe'|get-random) "https://www.quora.com"
For understanding the two used PowerShell cmdlets and how they work, open a PowerShell console window, execute there the following commands, and read entirely the two help pages displayed for the two cmdlets very carefully.
help start-process
help get-random
One batch file solution is:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set /A "Browser=%RANDOM% & 1"
if %Browser% == 0 (set "Browser=chrome") else set "Browser=firefox"
start "" %Browser%.exe "https://www.quora.com"
endlocal
The first two command lines just define the required execution environment completely and creates a new environment variables list as copy of the current environment variables list and the last line just results in restoring the initial execution environment and environment variables list. The second and the last command line could be omitted if it is no problem to depend on Windows defaults or what the process calling this batch file defines as execution environment.
The third line uses an arithmetic expression to apply on a random number a bitwise AND with 1 to get assigned to the environment variable Browser randomly either 0 or 1.
The third line could be also:
set /A Browser=%RANDOM% %% 2
This arithmetic expression divides a random number by two and gets the remainder 0 or 1 assigned to the environment variable Browser.
The fourth line uses an IF condition to redefine the environment variable Browser on having currently the value 0 with the string chrome and otherwise with the string firefox.
The fifth line uses command start to start either chrome.exe or firefox.exe as separate process on which cmd.exe does not wait for self-termination before continuation of processing of the batch file with passing the URL to started executable. "" defines an empty string as optional title for the console window not opened at all as the two browsers are Windows applications with a graphic user interface.
For understanding the used Windows Commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
help echo or echo /?
help endlocal or endlocal /?
help if or if /?
help set or set /?
help setlocal or setlocal /?
help start or start /?
See also:
An A-Z Index of Windows CMD commands
An A-Z Index of Windows PowerShell commands
Windows CMD Shell How-to guides and examples
Windows PowerShell How-to guides and examples
Where is "START" searching for executables?
powershell.exe does the same. PowerShell and CMD use the Windows kernel library function CreateProcess to start the Chrome or Firefox process.
So, I want to make a script that will execute 2 .bat files and start some .exe files.
However, the .bat files are supposed to keep running.
I have something like this :
pushd tools\wamp64
start wampmanager.exe
pushd ..\..\server\login
call startLoginServer.bat
pushd ..\test
call startTestServer.bat
start "C:\DEV\P2\Test\client" P2.bin
The problem is that call startLoginServer.bat will not exit and therefore, I'm stucked here.
How can I run my 2 .bat files and let them keep running.
(Ideally, I want them to run in 2 different command prompt windows)
Also, there is probably a better way to handle relative path than using pushd if you can correct me on this.
Thanks
You could use:
start "Wamp Manager" /B /D "%~dp0tools\wamp64" wampmanager.exe
start "Login Server" /B /D "%~dp0server\login" startLoginServer.bat
start "Test Server" /B /D "%~dp0server\test" startTestServer.bat
start "Text Client" /B /D "%~dp0" "C:\DEV\P2\Test\client.exe" P2.bin
Run in a command prompt window start /? for help on this command explaining the options.
"..." ... title for new console window which is optional, but must be often specified on program to start is or must be enclosed in double quotes. The START command in last command line in batch file code in question interprets C:\DEV\P2\Test\client as window title. It is also possible to use an empty window title, i.e. "" which is best if the started application is a Windows GUI application on which no console window is opened at all.
/B ... run without opening a new window, i.e. in "background". This option can be omitted to see what the started applications and batch files output to console if the executables are not Windows GUI applications.
/D "..." or also /D"..." defines the directory to set first as current directory before running the command specified next. %~dp0 references the directory of the batch file containing these commands. This path always ends with a backslash. Therefore no backslash must be added on concatenating the directory of the batch file with a file or folder name or path.
Run in a command prompt window call /? for help on %~dp0 explaining how arguments of a batch file can be referenced from within a batch file.
See also the answer on How to call a batch file that is one level up from the current directory? explaining in total four different methods to call or run a batch file from within a batch file.
Finally read also the Microsoft documentations about the Windows kernel library function CreateProcess and the structure STARTUPINFO used by cmd.exe on every execution of an executable without or with usage of its internal command start. The options of start become more clear on having full knowledge about the kernel function and the structure used on Windows to run a program.
The Eclipse IDE has a feature where one could run external tools. I use it to run batch scripts. Oddly if a batch script runs a powershell command, the powershell command will never exit until I hit enter. This is especially odd since it exits just fine when running in cmd. How should I correct my script so that it runs as expected via the eclipse external tools?
Current script (foo.bat):
#echo off
echo "Hello 1"
REM Configure this to your installation of maven.
SET "CMD=C:\foo.ps1"
REM Reformat args to be Powershell friendly.
SET "ARGS=%*"
SET "ARGS=%ARGS: =' '%"
PowerShell.Exe -Command "%CMD%" '%ARGS%'
echo "Hello 2"
EXIT /B
In cmd, I see "Hello 1", the output of %CMD%, and "Hello 2". In Eclipse, I see "Hello 1", the output of %CMD%, and then it hangs in the progress tab forever until I click the Console window and press the enter key.
I tried passing the -NonInteractive flag to Powershell. I tried having my Powershell script echo a newline at the end. Not sure how to get this to "just work".
Found the answer. I needed to add a NUL redirect to the end of my Powershell command. So it looks like this:
#echo off
REM Configure this to your installation of maven.
SET "CMD=C:\foo.ps1"
REM Reformat args to be Powershell friendly.
SET "ARGS=%*"
SET "ARGS=%ARGS: =' '%"
PowerShell.Exe -Command "%CMD%" '%ARGS%' < NUL
Note that I also removed the dubugging code from the script found in my question. If you add that code back in, you'll see that it echos everything now.
The problem: When I double click the .bat file it executes as expected. When I schedule it in Windows Task Scheduler it executes except the line that has cscript.
Content of .bat file:
#echo off
cls
cscript CSV_To_Excel.vbs c:\tableaudata\test.csv c:\tableaudata\test.xlsx
echo.file converted >>log.txt
What is throwing me off is the fact that log.txt gets created indicating that the .bat file is being executed. But .xlsx is not created. However, on manually double clicking .bat both log.txt and test.xlsx is created.
What could be the problem?
Resolved!! In the windows task scheduler I had to click "change user or group" button and add "Administrators" group.
To help debug the situation, add the following to the end of your cscript command line:
>>c:\MyCScriptOutput.txt 2>&1
Then, check to see if the c:\MyCScriptOutput.txt file has any error message(s) in it. If it does, please add this information (both the command line and the output) to your question.
I'm speculating, but the problem might be that cscript is trying and failing to run interactively, so you could try replacing "cscript" in your command line with "cscript //Nologo //B", to see if that fixes it.
The main problem is you don't specify full path to your CSV_To_Excel.vbs
Scheduler execute script from c:\windows\system32 (where schtasks.exe located)
So, your batch call to cscript should be
cscript %~dp0\CSV_To_Excel.vbs c:\tableaudata\test.csv c:\tableaudata\test.xlsx
echo.file converted >> %~dp0\log.txt
On my PC, VBS files are set (via the file association entries in the registry) to run using WScript. This is what I want, so that I can double click on a VBS file and not have a console window open. However, when I am using the Powershell command line, I would like VBS scripts to run using CScript (i.e., using "cscript /nologo myfile.vbs"). Is there a way to make Powershell do this, without affecting the double-click behaviour?
For single scripts, I could write a function for each one (function foo { cscript /nologo foo.vbs $args }) but that doesn't scale at all. I'm thinking of something like Take Command's "executable extensions" feature, that lets you set a specific action for a file extension (set .vbs=cscript /nologo).
I have the same problem for Python scripts, where again the default action doesn't do what I want (for some reason, it opens a second console window, rather than displaying output in the Powershell console) so a VBS-specific answer will only give me part of what I want :-(
Thanks,
Paul
The easiest thing i can think of is, to set an environment variable whenever you start Power Shell (does it have an autoexec feature?) let's call it "InPowerShell" and give it the value "YES".
Then create a .bat file like this:
if %InPowerShell%==YES (
cscript /nologo #*
) else (
wscript #*
)
Set all vbs files to open with this bat file. This way whenever you double click it it will be opened with wscript, and inside powershell will open with cscript.
(Note: I didn't test this)