Hide file extensions in PowerShell tab completion

One thing I have quickly discovered as I get acclimated to my new Windows machine is that by default the Windows Powershell CLI appends the executable file extension to the command that gets run, which is not the case on Linux or OSX.  That got me wondering if it is possible to modify this default behavior and remove the extension.  I’m going to ruin the surprise and let everybody know that it is definitely possible change this behavior, thanks to the flexibility of Powershell and friends.  Now that the surprise is ruined, read on to find out how this solution works.

To check which file types Windows considers to be executable you can type $Env:PathExt.

PS > $Env:PathExt
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW;.CPL

Similarly, you can type $Env:Path to get a list of places that Windows will look for files to execute by default.

PS > $Env:PATH
C:\Program Files\Docker\Docker\Resources\bin;C:\Python35\Scripts\;C:\Python35\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Co
ram Files\nodejs\;C:\Program Files\Git\cmd;C:\Program Files (x86)\Skype\Phone\;C:\Users\jmreicha\AppData\Local\Microsoft\WindowsApps;C:\Users\jmreicha\AppData\Local\atom\bin;C:\Users\jmreicha\AppData\Roaming\npm

The problem though, is that when you start typing in an extension that is part of this path, say python, and tab complete it, Windows will automatically append the file extension to the executable.  Since I am more comfortable using a *nix style shell it is an annoyance having to deal with the file extensions.

Below I will show you a hack for hiding these from you Powershell prompt.  It is actually much more work than I thought to add this behavior but with some help from some folks over at stackoverflow, we can add it.  Basically, we need to overwrite the functionality of the default Powershell tab completion with our own, and then have that override get loaded into the Powershell prompt when it gets loaded, via a custom Profile.ps1 file.

To get this working, the first step is to look at what the default tab completion does.

(Get-Command 'TabExpansion2').ScriptBlock

This will spit out the code that handles the tab completion behavior.  To get our custom behavior we need to override the original code with our own logic, which I have below (I wish I came up with this myself but alas).  This is note the full code, just the custom logic.  The full script is posted below.

$field = [System.Management.Automation.CompletionResult].GetField('completionText', 'Instance, NonPublic')
$source.CompletionMatches | % {
        If ($_.ResultType -eq 'Command' -and [io.file]::Exists($_.ToolTip)) {
            $field.SetValue($_, [io.path]::GetFileNameWithoutExtension($_.CompletionText))
        }
    }
Return $source

The code looks a little bit intimidating but is basically just looking to see if the command is executable and on our system path, and if it is just strips out the extension.

So to get this all working, we need to create a file with the logic, and have Powershell read it at load time.  Go ahead and paste the following code into a file like no_ext_tabs.ps1.  I place this in the Powershell path (~/Documents/WindowsPowerShell), but you can put it anywhere.

Function TabExpansion2 {
    [CmdletBinding(DefaultParameterSetName = 'ScriptInputSet')]
    Param(
        [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory = $true, Position = 0)]
        [string] $inputScript,

        [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory = $true, Position = 1)]
        [int] $cursorColumn,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 0)]
        [System.Management.Automation.Language.Ast] $ast,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 1)]
        [System.Management.Automation.Language.Token[]] $tokens,

        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 2)]
        [System.Management.Automation.Language.IScriptPosition] $positionOfCursor,

        [Parameter(ParameterSetName = 'ScriptInputSet', Position = 2)]
        [Parameter(ParameterSetName = 'AstInputSet', Position = 3)]
        [Hashtable] $options = $null
    )

    End
    {
        $source = $null
        if ($psCmdlet.ParameterSetName -eq 'ScriptInputSet')
        {
            $source = [System.Management.Automation.CommandCompletion]::CompleteInput(
                <#inputScript#>  $inputScript,
                <#cursorColumn#> $cursorColumn,
                <#options#>      $options)
        }
        else
        {
            $source = [System.Management.Automation.CommandCompletion]::CompleteInput(
                <#ast#>              $ast,
                <#tokens#>           $tokens,
                <#positionOfCursor#> $positionOfCursor,
                <#options#>          $options)
        }
        $field = [System.Management.Automation.CompletionResult].GetField('completionText', 'Instance, NonPublic')
        $source.CompletionMatches | % {
            If ($_.ResultType -eq 'Command' -and [io.file]::Exists($_.ToolTip)) {
                $field.SetValue($_, [io.path]::GetFileNameWithoutExtension($_.CompletionText))
            }
        }
        Return $source
    }    
}

To start using this tab completion override file right away, just source the file as below and it should start working right away.

. .\no_ext_tabs.ps1

If you want the extensions to be hidden every time you start a new Powershell session we just need to create a new Powershell profile (more reading on creating Powershell profiles here if you’re interested) and have it load our script. If you already have a custom profile you can skip this step.

New-Item -path $profile -type file -force

After you create the profile go ahead and edit it by adding the following configuration.

# Dot source not_ext_tabs to remove file extensions from executables in path
. C:\Users\jmreicha\Documents\WindowsPowerShell\no_ext_tabs.ps1

Close your shell and open it again and you should no longer see the file extensions.

There is one last little, unrelated tidbit that I discovered through this process but thought was pretty handy and worth sharing with other Powershell N00bs.

Powershell 3 and above provides some nice key bindings for jumping around the CLI, similar to a bash based shell if you are familiar or have a background using *nix systems.

Powershell key shortcuts

You can check the full list of these key bindings by typing ctrl+alt+shift+? in your Powershell prompt (thanks Keith Hill for this trick).

Read More

QBet Casino: Erleben Sie das Beste von Q Bet und QBet Casino Logins in Deutschland!

In der aufregenden Welt der Online-Casinos steht QBet Casino an vorderster Front und bietet eine unvergleichliche Erfahrung für Spieler in Deutschland. Mit einer Vielzahl von Spielen, beeindruckenden Boni und einer benutzerfreundlichen Plattform bietet QBet alles, was das Spielerherz begehrt.

Warum QBet Casino die beste Wahl ist

Für viele Spieler ist die Wahl des richtigen Online-Casinos entscheidend. QBet zeichnet sich durch seine Transparenz, hohen Sicherheitsstandards und eine riesige Auswahl an Spielen aus. Egal, ob Sie ein Fan von Spielautomaten, Tischspielen oder Live-Casino-Erlebnissen sind, bei QBet Casino werden Sie fündig.

Casino Erlebnis

Einfacher Zugang zu QBet Deutschland

Der Zugriff auf QBet Casino ist denkbar einfach. Dank der intuitiven QBet Casino Login-Oberfläche können Sie schnell und sicher auf Ihr Konto zugreifen und Ihr Spielerlebnis personalisieren. Ihr Abenteuer beginnt mit nur wenigen Klicks.

QBet Casino in Deutschland

Die Beliebtheit von QBet Deutschland ist auf die attraktive Spielumgebung und die zahlreichen Vorteile zurückzuführen. Egal, ob Sie ein erfahrener Spieler oder ein Neuling sind, QBet deutschland bietet für jeden etwas.

Unser engagiertes Kundensupport-Team steht Ihnen rund um die Uhr zur Verfügung, um sicherzustellen, dass Ihr Spielerlebnis reibungslos verläuft. Freuen Sie sich auf ein sicheres, unterhaltsames und gewinnbringendes Spielerlebnis bei QBet.

Read More

Experience the Thrill with Ninewin: Your Ultimate Ninewin Casino and App Guide

Welcome to the exciting world of Ninewin, where opportunities and entertainment abound. Whether you’re a seasoned gambler or new to the scene, the Ninewin casino offers a myriad of options to keep you engaged. In this article, we’ll delve into the ins and outs of the Ninewin app and explore how to make the most of your experience.

What Makes Ninewin Casino Stand Out?

Ninewin casino has rapidly become a go-to destination for online gaming enthusiasts. Its user-friendly interface allows for seamless navigation, and the rich variety of games caters to every taste. Be it slot games, poker, or roulette, the thrill never stops.

Ninewin Casino

Smooth Navigation with the Ninewin App

The Ninewin app is designed to offer unparalleled ease of use. With just a few taps, users can access their favorite games, check their balance, and make deposits or withdrawals. The convenience of the Ninewin app ensures that players can enjoy their gaming experience anytime, anywhere.

Getting Started: How to Navigate Ninewin Casino Login

Starting your adventure with Ninewin is simple. The Ninewin casino login page is intuitively designed to get you into the action swiftly. Existing users can log in using their credentials, while new users can effortlessly sign up and create an account.

A Secure Gaming Environment

Security is of utmost importance at Ninewin. With top-tier encryption and secure payment methods, players can have peace of mind that their data and transactions are protected. This commitment to safety ensures that players can focus on the excitement of the games.

Special Promotions and VIP Programs

Ninewin frequently offers special promotions to enhance the player experience. From welcome bonuses to exclusive VIP programs, these rewards provide additional value and exciting opportunities to boost your gaming experience.

Overall, Ninewin stands out as a premier destination for online gaming. Don’t miss your chance to engage with this dynamic platform. Visit the Ninewin Casino now to start your thrilling journey.

Engage with the Community

One of the unique aspects of Ninewin is its vibrant community. Players can share their experiences, tips, and strategies, fostering a sense of camaraderie and excitement. The in-game chat features and forums are perfect places to connect with fellow enthusiasts.

See How It Works

In conclusion, Ninewin is not just another online casino; it’s a hub of excitement and innovation. Whether accessing through the app or directly from your desktop, the world of Ninewin Casino is just a click away. Enjoy the journey and good luck!

Read More

Scopri le Offerte Irresistibili su Betn1: App, Slot, Casinò e Bonus Online

Betn1 Casino

Benvenuti nel mondo di Betn1, la piattaforma all’avanguardia per scommesse, giochi online, e casinò. Se sei un appassionato di giochi d’azzardo, troverai tutto quello che desideri, dalle scommesse sportive a una vasta selezione di casinò online. In questo articolo scopriamo in dettaglio le caratteristiche e le offerte uniche di Betn1.

Accedi Facilmente con Betn1 Login

Registrarsi e iniziare a giocare non è mai stato così semplice. L’uso del Betn1 login ti permette di accedere rapidamente a tutti i tuoi giochi preferiti, anche dalla comodità della Betn1 app che è progettata per offrire un’esperienza utente fluida e intuitiva.

Un Mondo di Emozioni con Betn1 Slot

Le Betn1 slot offrono un’ampia gamma di giochi con temi coinvolgenti, grafiche straordinarie e vincite emozionanti. Che tu sia un fan delle slot classiche o moderne, troverai sicuramente il gioco perfetto per te. E non dimenticare di provare la fortuna con i jackpot progressivi!

Aumenta il tuo Budget con il Betn1 Bonus

Uno degli aspetti più attraenti di Betn1 è senza dubbio il bonus che offre ai nuovi utenti e ai giocatori regolari. Scopri come le offerte bonus possono trasformare le tue giocate in grandi opportunità di vincita.

Esplora il Fascino del Betn1 Casino

Il Betn1 casinò è un sogno diventato realtà per ogni appassionato di giochi d’azzardo. Con una vasta gamma di giochi da tavolo, roulette e tanto altro, il divertimento è assicurato. Non perdere l’occasione di sperimentare l’atmosfera elettrizzante dei casinò dal vivo.

Visita Betn1 online per iniziare il tuo viaggio nel mondo delle scommesse e del casinò!

Esperienza Video di Betn1

Guarda il nostro ultimo video per un’anteprima dei giochi e delle caratteristiche disponibili su Betn1:

Read More

Descubre el Mundo del 777 Casino: Jugando Online, Inicio de Sesión, App y Slots

El 777 casino es una de las plataformas más emocionantes para los entusiastas del juego en línea. Con una amplia gama de opciones de entretenimiento, este casino ha capturado la atención de jugadores en todo el mundo. En este artículo, exploraremos las características que hacen del 777 casino online una elección ideal, cómo hacer el 777 casino login, el uso de la app y la variedad de 777 casino slot disponibles para ti. ¡Acompáñanos en este viaje de descubrimiento!

Aplicación de Casino 777

777 Casino Online: Una Breve Introducción

Desde su creación, el 777 casino online ha ofrecido una experiencia de juego sin igual. Con su diseño elegante y fácil de usar, los jugadores pueden disfrutar de una variedad de juegos que van desde las clásicas tragamonedas hasta emocionantes juegos de cartas y ruleta. Este nivel de variedad y calidad es lo que distingue al casino en línea 777 de sus competidores.

Cómo Hacer el 777 Casino Login de Forma Segura

Acceder a tu cuenta en el 777 casino es un proceso sencillo y seguro. Los usuarios deben primero registrarse proporcionando sus datos necesarios. Una vez registrados, el inicio de sesión en el 777 casino login se realiza introduciendo el nombre de usuario y la contraseña. Además, el casino implementa tecnologías de encriptación de última generación para garantizar que tus datos personales estén siempre protegidos.

Explorando la 777 Casino App

Para aquellos que prefieren llevar el casino a cualquier lugar, la 777 casino app es la solución perfecta. Esta aplicación ofrece todas las prestaciones del sitio web con la comodidad de acceder desde cualquier dispositivo móvil. La aplicación está disponible tanto para Android como para iOS, y permite a los jugadores disfrutar de sus juegos favoritos, realizar depósitos y retiros fácilmente, y aprovechar las promociones exclusivas solo para usuarios de la app.

Un Vistazo Rápido a las 777 Casino Slot

Las tragamonedas o 777 casino slot son sin duda el atractivo principal para muchos jugadores. Desde temáticas clásicas hasta las más innovadoras, las tragamonedas del casino 777 brindan una experiencia de entretenimiento inigualable. El casino se asegura de actualizar su colección constantemente, ofreciendo así siempre algo nuevo para descubrir. La combinación perfecta de gráficos envolventes, sonidos realistas y generosos botes hacen que los jugadores regresen por más.

Conclusión

En resumen, el 777 casino ofrece una experiencia de juego inigualable. Ya sea que los jugadores prefieran el 777 casino online, utilizar la innovadora 777 casino app, o disfrutar de una variedad de juegos a través de inicio de sesión seguro en el 777 casino login, siempre hallarán algo para satisfacer sus deseos de juego. No cabe duda de que, con su amplia selección de 777 casino slot, este casino se ubica entre los preferidos de los jugadores. ¡No esperes más y sumérgete en la diversión que te espera en el 777 casino!

Read More