How to keep the shell window open after running a PowerShell script? - active-directory

I have a very short PowerShell script that connects to a server and imports the AD module. I'd like to run the script simply by double clicking, but I'm afraid the window immediately closes after the last line.
How can I sort this out?

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.
One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
Global Fix: Change your registry key by adding the -NoExit switch to always leave the PowerShell Console window open after the script finishes running.
Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command
Description: Key used when you right-click a .ps1 file and choose Open With -> Windows PowerShell.
Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command
Description: Key used when you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).
Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
See my blog for more information and a script to download that will make the registry change for you.

Errr...
I should have known:
powershell -noexit <path\script>
and that's all there's to it :)

The solution below prevents the script from closing when running Powershell ISE and allows the script to close otherwise.
# If running in the console, wait for input before closing.
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}

Just add pause on a new line at the bottom of the script, as in a batch file.

In my own case, I wanted to add powershell to context menu on windows 7. That is right clicking on a folder or inside a folder to get a menu to launch Powershell window without it closing after launch. The answers here helped me do just that and I want to share it here incase it helps someone else.
Launch registry editor by pressing WIN + R
type regedit.exe and hit enter
Navigate to HKEY_CLASSES_ROOT\Directory\Background\shell
Right click on shell and create a key give it a name e.g PowershellHere
On the right pane, double click on Default and provide a descriptive name e.g Powershell Here
Right click on the PowershellHere key you created earlier and create a new key and name it "command" please make sure you name it exactly so but without the quotes.
On the right pane, double click on Default and then type the command below
C:\Windows\system32\WindowsPowerShell\v1.0\PowerShell.exe -noexit -Command CD '"%1"'
-noexit flag makes sure that the Powershell windows does not close again immediately after launch
'"%1"' flag represents the folder you right clicked
-Command CD '"%1"' will ensure the Powershell changes into the right clicked directory.
To make the right click work inside a folder meaning right clicking an empty space inside a folder, repeat the steps but this time, the registry location is:
HKEY_CLASSES_ROOT\Directory\shell
And the command is:
C:\Windows\system32\WindowsPowerShell\v1.0\PowerShell.exe -noexit
Tested on windows 7 ultimate sp1 but I think I might work for later versions of Windows as well

You can add pause at the end of your script if you just want the window to stay open, or you can add powershell if you want to be able to run commands afterwards (obviously don't do the second option if anyone else will use your code).

Related

How to run cypher shell from Run dialog?

The cypher-shell.bat is located at D:\GitHub\cypher-shell\cypher-shell.bat. Neither of these commands starts the shell when I put it in the Run dialog:
pwsh D:\GitHub\cypher-shell\cypher-shell.bat: PowerShell opens and exits immediately
pwsh -wd D:\GitHub\cypher-shell\cypher-shell.bat: PowerShell doesn't exit but shows this error: Set-Location: Cannot find path 'D:\GitHub\cypher-shell\cypher-shell.bat' because it does not exist.
pwsh -f D:\GitHub\cypher-shell\cypher-shell.bat: PowerShell opens and exits immediately
How should I do this properly?
I actually have added D:\GitHub\cypher-shell to my path. Running pwsh "& cypher-shell", pwsh ^& cypher-shell, or "%ProgramFiles%\PowerShell\7\pwsh.exe" "& 'D:\GitHub\cypher-shell\cypher-shell.bat'"in Run dialog the terminal flashes for a moment and closes. In the moment it opens I can see it messages a red error.
The reason I want to use this in PowerShell because it supports more features, like copypasting or selecting text with keyboard only. The commands are also more convenient than CMD.
FYI: about Pwsh - PowerShell | Microsoft Docs

Conemu startup with a task opening multiple tabs

Is there a way with conEmu to by default open a number of different tabs?
I saw this page explaining how to do this with splits,
and I realize I can do Ctrl + T, 1, Enter, but I was hoping there was a way to do this automatically!
"%GIT_HOME%\usr\bin\sh.exe" --login -i -cur_console:t:"repo1":C:"%GIT_HOME%\git-bash.exe":d:"%USERPROFILE%\code\repo1"
"%GIT_HOME%\usr\bin\sh.exe" --login -i -new_console:t:"repo2":C:"%GIT_HOME%\git-bash.exe":d:"%USERPROFILE%\code\repo2"
"%GIT_HOME%\usr\bin\sh.exe" --login -i -new_console:t:"repo3":C:"%GIT_HOME%\git-bash.exe":d:"%USERPROFILE%\code\repo3"
Yes, it is possible but not via the settings Dialog of Conemu. You need a small config file
Create Config File
Go to Conemu installation directory (like C:\Program Files\ConEmu)
Create file startup.txt
List the consoles you want to open at startup. For example
>C:\Program Files\staab\Git\bin\bash.exe
>C:\WINDOWS\system32\cmd.exe
will open Git Bash and cmd at startup (in that order). If you want to set the startup directories for each console you can do this too:
>C:\Program Files\staab\Git\bin\bash.exe -new_console:d:C:\example\path
>C:\WINDOWS\system32\cmd.exe -new_console:d:C:\other\path
Start Conemu with that config file
Create a new desktop shortcut for the ConEmu64.exe (or ConEmu.exe if you use the 32-Bit version)
Right click > Properties on that shortcut.
Add /cmd #startup.txt to the target
Now you can link that shortcut to your task bar or put it in the autostart folder of your computer to start Conemu with those consoles right after login.
Update 1: Name for Tab
I just found out that you can also set the name of all the tabs on startup :-)
>C:\Program Files\staab\Git\bin\bash.exe -new_console:d:C:\example\path -cur_console:t:NAME_OF_TAB
Update 2: Admin Rights
And this is how you give admin rights to the tabs of your choice:
>C:\Program Files\staab\Git\bin\bash.exe -new_console:d:C:\example\path -new_console:a
Don't use this more than necessary, because you have to confirm admin rights for each window individually.

How to update Target (right click properties) of an .exe using a batch script?

I would like to update the Target of an .exe using my batch file. Is it possible?
Basically, i would like to make my app auto-login by adding userid and password to it and i don't want to manually do this for every installation that i do.
So from Target: C:\Softwarebin\Software.exe to Target: "C:\Softwarebin\Software.exe -user:app -passwd: app1"
At the moment, i have to do this manually everytime i install our software for the users by right clicking the desktop shortcut and editing the Target field as above. It would be great to have a batch command which i could include in my install.bat file which would update this for me as well after the installation is complete.
Any suggestions please?
Thanks
irish
You can't change the target of the .exe itself, however, you can make\modify a shortcut with vbscript and run it from a batch-file the following way:
Set shell = CreateObject("WScript.Shell")
Set prog_shortcut = shell.CreateShortcut("Your_shortcut_location\Shortcut.lnk")
prog_shortcut.TargetPath = "C:\Softwarebin\Software.exe -user:app -passwd: app1"
prog_shortcut.Save
Notice that CreateShortcut also modify an existing shortcut, so it should do the trick.
You can run the vbscript from command afterwards if you need.

Run Batch File On Start-up

Is there a way to start multiple programs in a batch file on system start-up? In addition to that, in that batch file, I would like to be able to say: Once I execute a program, wait until that program completely loads, and execute the next listed program.
Any help would be appreciated.
I had the same issue in Win7 regarding running a script (.bat) at startup (When the computer boots vs when someone logs in) that would modify the network parameters using netsh. What ended up working for me was the following:
Log in with an Administrator account
Click on start and type “Task Scheduler” and hit return
Click on “Task Scheduler Library”
Click on “Create New Task” on the right hand side of the screen and set the parameters as follows:
a. Set the user account to SYSTEM
b. Choose "Run with highest privileges"
c. Choose the OS for Windows7
Click on “Triggers” tab and then click on “New…”
Choose “At Startup” from the drop down menu, click Enabled and hit OK
Click on the “Actions tab” and then click on “New…”
If you are running a .bat file use cmd as the program the put
/c .bat
In the Add arguments field
Click on “OK” then on “OK” on the create task panel and it will now
be scheduled.
Add the .bat script to the place specified in your task event.
Enjoy.
To run a batch file at start up: start >> all programs >> right-click startup >> open >> right click batch file >> create shortcut >> drag shortcut to startup folder.
The path to the folder is : [D|C]:\Profiles\{User}\‌​AppData\Roaming\Micro‌​soft\Windows\Start Menu\Programs\Startu‌​p
Go to Run (WINDOWS + R) and
Type
shell:startup, paste your .bat file there !
To start the batch file at the start of your system, you can also use a registry key.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Here you can create a string. As name you can choose anything and the data is the full path to your file.
There is also the registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
to run something at only the next start of your system.
There are a few ways to run a batch file on start up. The one I usually use is through task scheduler. If you press the windows key then type task scheduler it will come up as an option (or find through administerative tools).
When you create a new task you can chose from trigger options such as 'At log on' for a specific user, on workstation unlock etc. Then in actions you select start a program and put the full path to your batch script (there is also an option to put any command line args required).
Here is a an example script to launch Stack Overflow in Firefox:
#echo off
title Auto launch Stack Overflow
start firefox http://stackoverflow.com/questions/tagged/python+or+sql+or+sqlite+or+plsql+or+oracle+or+windows-7+or+cmd+or+excel+or+access+or+vba+or+excel-vba+or+access-vba?sort=newest
REM Optional - I tend to log these sorts of events so that you can see what has happened afterwards
echo %date% %time%, %computername% >> %logs%\StackOverflowAuto.csv
exit
RunOnce
RunOnce is an option and have a few keys that can be used for pointing a command to start on startup (depending if it concerns a user or the whole system):
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
setting the value:
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v MyBat /D "!C:\mybat.bat"
With setting and exclamation mark at the beginning and if the script exist with a value different than 0 the registry key wont be deleted and the script will be executed every time on startup
SCHTASKS
You can use SCHTASKS and a triggering event:
SCHTASKS /Create /SC ONEVENT /MO ONLOGON /TN ON_LOGON /tr "c:\some.bat"
or
SCHTASKS /Create /SC ONEVENT /MO ONSTART/TN ON_START /tr "c:\some.bat"
Startup Folder
You also have two startup folders - one for the current user and one global.
There you can copy your scripts (or shortcuts) in order to start a file on startup
::the global one
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
::for the current user
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
1. Copy the following lines to Notepad.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Users\toto\your_file.bat" & Chr(34), 0
Set WshShell = Nothing
Note: Replace the batch file name/path accordingly in the script according to your requirement.
2. Save the file with .VBS extension, example launch_bat.vbs
3. Create new .bat file, in our case your_file.bat
4. Write the content of your .bat file.
Example:
#echo off
php c:\laragon\www\my_app\artisan serve --host=127.0.0.1 --port=8000
5. Run your_file.bat and ejoy :)
If your Windows language is different from English, you can launch the Task Scheduler by
Press Windows+X
Select your language translation of "Computer Management"
Follow the instruction in the answer provided by prankin
Another option would be to run the batch file as a service, and set the startup of the service to "Automatic" or "Automatic (Delayed Start)".
Check this question for more information on how to do it, personally I like NSSM the most.

Prevent batch file in CMD from closing without using Pause

Currently I want to run a batch file that fires the command git log and show me that log.
After that I need to be able to commit and view the status so this prompt may not disappear after a key press.
I've searched the net and the only answer people have is pause which close the prompt after a keypress.
Does anyone have the solution for me? Currently I made a shortcut to cmd.exe and made the target my folder, but I want to execute some commands also.
Thanks in advance.
This (below) tested OK in Windows 7. To exit the window it creates, type "exit" when done.
start cmd /K "cd \[the-target-folder] && git log"
Where:
[the-target-folder] you replace with your target folder
Note:
&& lets you run two commands on one line
/K is a parameter to the cmd shell program which which carries out the command specified by string and remains.

Resources