Accessing PowerShell history with up-arrow - windows

I recently switched to powershell since my Cygwin bash started giving me senseless compilation errors when using maven. I've found how to save and restore my command history in (https://stackoverflow.com/questions/9259723/is-there-a-windows-shell-tool-can-keep-history), which seems to work (using "History" will show the recent commands after a clean start).
What I can't seem to do is access this history with the up arrow like you would if the command was used in the current session.
Any ideas?

I would suggest killing this old habit (I know, they die hard) and using PowerShell specific feature that is build for that. It's in fact pretty awesome. This is #*[tab], there are 2 options here (tab in brackets ([tab]) means that the tab button should be pressed):
#pattern_from_command[tab]
-> Powershell cycles through all commands in history that contain "pattern_from_command".
-> EG: In Powershell: type #echo, press tab -> Powershell cycles through all commands in history that contain "echo" (of course if any).
#<id>[tab]
-> Powershell completes command with id <id>.
-> EG: In Powershell: type #3, press tab -> Powershell writes the third (3) command in history to command line (though not executing it directly, just press enter to execute it).
I know it's not the same as you would do in bash, but I think it's worth trying and getting used to.
EDIT: It appears that recent versions of PSReadLine removed that functionality. You are better off with functionality in PSReadLine anyways, but if you want to give it a try in regular console, and it doesn't work - just
Remove-Module -Name PSReadLine
Functionality still works in any host that doesn't load PSReadLine by default (e.g. PowerShell ISE).

As of October 2013, this is now possible using the wonderful PSReadline module: http://github.com/lzybkr/PSReadLine
You'll still need to save your history when your powershell session exits and load it in your profile.ps1 prior to loading PSReadline (see http://technet.microsoft.com/en-us/library/ee156792.aspx). You can register a hook to save your history when PowerShell exists using a hook like this: Powershell profile "on exit" event?. Unlike vanilla PowerShell, PSReadLine allows the up/down keys to access this history buffer.

Like say #jhclark it is now possible
You have all the documentation for installation in the official GitHub : https://github.com/PowerShell/PSReadLine
You will have to follow the whole tutorial well and pay attention to:
remove -AllowPrerelease arg if you have error
add this line Import-Module 'PSReadLine' in your profile code $PROFILE for example to open your profile conf with vscode
Close all shell after you install PSReadLine if you want all work fine
Launch this two lines if you want the fleche to search in the history like on Linux because that is, I think, what most people are looking for:
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward
by default are the key combinations F8 and SHIFT + F8 which are configured by default
You can see the conf with that :
Get-PSReadLineKeyHandler

You cannot. There is no API for accessing a console program's history.

Related

Is it possible to spool to a file everything is typed from a windows terminal and its output?

I'm wondering whether is possible or not to spool to a file everything is typed from a Windows CMD terminal in order to record my work activity. I need to spool to the same file even what is performed from other interactive command line tools invoked from the terminal like Oracle SQL*Plus or any progamming language REPL like tool.
The goal is mainly to save some investigation activities made on a server for troubleshooting performance issues, so I can review all the metrics collected for each step after the issue is eventually disappeared.
Even if not useful at the moment, it would be nice to know how to do the same on both Unix/Linux and Mac OS.
You could start a PowerShell session and use:
Start-Transcript -Path $Env:USERPROFILE/mylog.txt
& "$Env:ComSpec" /K
REM enter commands and run batch files...
EXIT
Stop-Transcript
Get-Content -Path "$Env:USERPROFILE/mylog.txt"
The commands will not be in the mylog.txt file until after you exit the cmd.exe shell. I have no idea if it will work in the same way on Linux or Mac. I have not thought about it much.
If you need to record multiple shell sessions, they will probably need to write to different log files.

code.exe ignoring command-line arguments

I hope this is an easy fix, but I couldn't find any documentation or other posts on the matter. I'm trying to write a script (cmd or pwsh) that will launch vscode with my preferences on a portable install.
When trying to execute vscode's code.exe with any arguments, it ignores them and just launches the program as if I had typed nothing else. I'm following this doc in my testing. Using alias switches doesn't work, either. The only argument that does seem to process is if I include a path.
code.exe --help
code.exe --version
Additionally, after launching code.exe, the console kind of hangs, then vscode status messages are sent to that console (even without use of the --wait switch). If I close the console, vscode shuts down. Is there a way to work around this?
When using Code via shell (cmd or pwsh), it does not use Code.exe, but the script/batch files located under Bin folder (code.cmd). These are the applications which really recognizes the command line switches.
This is not entirely clear in the Command Line Documentation page, but looking closer at the Note you will see that it does say the Program Files\Microsoft VS Code\bin folder.

Windows 10 console colors not working (Virtual terminal control character sequences)

Console's text colors are not working in Windows 10 build 15063.296.
I have dug into it a bit and found myself lost. Here's everything I've found...
From several discussions, it seems that the support for 'Virtual terminal sequences' or 'control character sequences' was removed in recent versions of Windows 10 (#1, #2). Some also adviced to downgrade a git version (that didn't work for me).
I tried to copy a cmd.exe from my other machine, the version was 10.0.10586.0 and the coloring worked, however, upon further reading and experimenting, I am no longer sure where the problem lies.
See compared the outputs of ls --color=auto
git\git-cmd.exe, git\git-bash.exe, windows' original cmd.exe and older cmd.exe
According to this site, the support for coloring does not lie in a command window, but in a conhost.exe, which brings up the question --Why does it work in some consoles and in some not?
If you start powershell.exe from cmd.exe, it will inherit the conhost settings since it’s attaching to a previously created console, not allocating a new one; this also enables escape sequences in powershell.exe.
Given this quote, I tried the following that only deepened my confusion.
I run a ls --color=auto command in each cmd version, then tried running older cmd from newer and vice versa and got the following results.
(red underline is cmd v15063, green underline is cmd v10586)
old, new from old
new, old from new
/EDIT I've made few more experiments...
What is interesting/confusing is the different result of type and cat and a compared result of ls --color=auto with the same content typed from a file.
Old console
New console
Console Virtual Terminal Sequences msdn
ANSI.SYS historical documentation
As for now, I have "fixed" it by replacing the newer cmd_10.0.15063.0 with the older cmd_10.0.10586.0 that I copied from my old system. If you have run a windows upgrade, you may find an older cmd version in C:\Windows.old\Windows\System32\cmd.exe. (the folder is hidden)
To replace the system's cmd.exe you will need to take ownership of the file Properties -> Security -> Advanced, there at the top Owner: TrustedInstaller (Change), set to Administrators, then give Administrators full permissions in Permissions -> Change permissions -> Administrators -> Edit -> Full control.

Delete gnome terminal configuration

I made a mistake in my gnome terminal configuration. I entered a command to start with in the preferences, but that command fails, and now all I get is a window that opens and closes right away, and I basically can't use gnome terminal anymore :-( Is there any way I can remove the configuration file and restart fresh??
Thanks!
Open the XTerm (Standard terminal for linux) and enter this command
gnome-terminal -e bash
It opens the gnome-terminal. Open profile preferences and configure your terminal to "Hold the terminal open".
Editing preferences
$HOME/.gconfd/saved_state
the above file might be of interest depending on exactly what configuration you changed. Of course, it holds configuration from other programs as well.
If you are on the newer gnome terminal that uses dconf, it's a little trickier, but still doable:
Profiles are stored with a UUID, you need to find the UUID of the profile to remove:
dconf dump /org/gnome/terminal/ | less
Search for a visible-name='...' entry matching the profile you want to remove. Look above that for the section header like [legacy/profiles:/:...]. The full name of the item you want to delete is thus /org/gnome/terminal/legacy/profiles:/:.... Delete it thus:
dconf reset -f /org/gnome/terminal/legacy/profiles:/:...
Side note: This Q&A probably should be moved to unix.stackexchange.com.

How do I make my Perl scripts act like normal programs on Windows?

I want my Perl scripts to behave just like any other executable (*.exe file).
When I double-click on myscript.pl I want it to execute instead of opening in a text editor.
I want to run myscript.pl instead of perl myscript.pl.
I really want to run myscript instead of myscript.pl.
I want to run program | myscript instead of program | perl myscript.pl.
I want to be able to run my script via drag & drop.
There are a number of changes you have to make on Windows to make all of
these things work. Users typically stumble upon things that don't work one at
a time; leaving them confused whether they've made an error, there's a bug in
Perl, there's a bug in Windows, or the behavior they want just isn't possible.
This question is intended to provide a single point of reference for making
everything work up front; ideally before these problems even occur.
Related questions:
How do I make Perl scripts recognize parameters in the Win32 cmd console?
Running a perl script on windows without extension
Perl execution from command line question
How can I read piped input in Perl on Windows?
Perl on Windows, file associations and I/O redirection
How do I create drag-and-drop Strawberry Perl programs?
Note: The actions below require administrative privileges. For
steps utilizing the command prompt it must be launched via "Run as
administrator" on Windows Vista / Windows 7.
Associate *.pl files with perl
Run the following commands at a shell prompt:
assoc .pl=PerlScript
ftype PerlScript=C:\bin\perl.exe "%1" %*
Replace C:\Perl\bin\perl.exe with the path to your Perl installation. This
enables you to run myscript.pl instead of perl myscript.pl.
Default install locations are:
ActivePerl: C:\Perl
Strawberry Perl: C:\Strawberry
Add .PL to your PATHEXT environment variable.
This makes Windows consider *.pl files to be executable when searching your
PATH. It enables you to run myscript instead of myscript.pl.
You can set it for the current cmd session
set PATHEXT=%PATHEXT%;.PL
To set it permanently (under Windows Vista or Windows 7)
setx PATHEXT %PATHEXT%;.PL
Under Windows XP you have to use the GUI:
Right-click My Computer, and then click Properties.
Click the Advanced tab.
Click Environment variables.
Select PATHEXT, then click Edit.
Append ;.PL to the current value.
Make I/O redirection work
I/O redirection (e.g. program | myscript) doesn't work for programs started
via a file association. There is a registry patch to correct the problem.
Start Registry Editor.
Locate and then click the following key in the registry:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
On the Edit menu, click Add Value, and then add the following registry value:
Value name: InheritConsoleHandles
Data type: REG_DWORD
Radix: Decimal
Value data: 1
Quit Registry Editor.
Warning: In principle, this should only be necessary on Windows XP. In my experience it's also necessary in Windows 7. In Windows 10 this is actively harmful—programs execute but produce nothing on stdout/stderr. The registry key needs to be set to 0 instead of 1.
See also:
STDIN/STDOUT Redirection May Not Work If Started from a File Association
Perl Scripts on Windows 10 run from Explorer but not Command Prompt
If patching the registry isn't an option running program | perl -S myscript.pl
is a less annoying work-around for scripts in your PATH.
Add a drop handler
Adding a drop handler for Perl allows you to run a Perl script via drag & drop;
e.g. dragging a file over the file icon in Windows Explorer and dropping it
there. Run the following script to add the necessary entries to the registry:
use Win32::TieRegistry;
$Registry->Delimiter("/");
$perlKey = $Registry-> {"HKEY_CLASSES_ROOT/Perl/"};
$perlKey-> {"shellex/"} = {
"DropHandler/" => {
"/" => "{86C86720-42A0-1069-A2E8-08002B30309D}"
}};
Convert your perl scripts into batch files using pl2bat once they are ready to be run by users.
The trick works through the perl -x switch which, according to perldoc perlrun, makes Perl search for the first line looking like #!.*perl.
After following the instructions in the accepted answer, a double click still led to .pl files opening with Notepad in Windows 10 — even when perl.exe was set as the default file handler.
After finding Jack Wu's comment at ActivePerl. .pl files no longer execute but open in Notepad instead I was able to run perl scripts on double-click as such:
Select and right-click a .pl file
Use the "Open With" submenu to "Choose another app"
Select "Always use this app to open .pl files" (do this now – you won't get the chance after you have selected a program)
Scroll to the bottom of the "Other options" to find "More apps", and select "Look for another app on this PC"
Navigate to C:/path/to/perl/bin/ and select Perl5.16.3.exe (or the equivalent, depending on which version of Perl you have installed: but not Perl.exe)
Then the Perl icon appears next to .pl files and a double-click leads to them opening in Perl every time, as desired.
I tried the assoc and ftype methods and they didn't work for me.
What worked was editing this registry key:
Computer\HKEY_CURRENT_USER\Software\Classes\Applications\perl.exe\shell\open\command
It was set to:
"C:\Perl64\bin\perl.exe" "%1"
When it should be:
"C:\Perl64\bin\perl.exe" "%1" %*
It is the same content as the ftype, but for arcane windows reasons, I had to set it there too.
Like some others, I had set 'assoc' and 'ftype', but also had set Notepad text editor via the GUI, and when I tried to execute a script via the command line, Windows invoked Notepad to edit the script instead of running my script.
Using the GUI to instead point the .pl file association to the script-running executable was not much of an improvement, since it would invoke the executable on my script, but would pass no command-line arguments (even when I invoked my script from the command line).
I finally found salvation here which advised me to delete some registry keys.
Key quote:
"The problem is that if you have already associated the program with the extension via the Open With dialog then you will have created an application association, instead of a file extension association, between the two. And application associations take precedence."
In my case, following the instructions to use RegEdit to delete
HKEY_CLASSES_ROOT \ Applications \ perl.exe
where perl.exe is the name of my Perl executable, and then also deleting:
HKEY_CLASSES_ROOT \ .pl
seemed to solve my problem, and then (after re-executing 'assoc' and 'ftype' commands as shown in other answers) I could then execute scripts from cmd.exe and have them run with access to their command-line parameters.
Some other related information here.

Resources