
A Saner Windows Command Line - japaget
http://futurice.com/blog/a-saner-windows-command-line-part-1
======
diego_moita
To hear bash-people to call Powershell "non-intuitive" sounds like those
immigrants that go to a foreign land, refuse to learn the local language and
insist on the natives to understand their immigrant language. Or like
programmers that think that every programming language should have the C
syntax.

Bash and Unix commands are only "intuitive" after years of practice;
Powershell is not different. And it doesn't have any obligation of being equal
to bash.

~~~
tacos
Windows fanboy here. Powershell made the mistake of combining a bad command
prompt with a bad scripting language. It is not a "shell" at all. It is bad
Python.

The excessive verbosity and object safety is _great_ for admin scenarios where
you don't suddenly destroy your corporate email transition because of a VP
with an apostrophe in her name. But at that point perhaps you should just use
C# instead?

But for everything else it just looks nuts to outsiders. That's why even the
MS developer groups are releasing command line tools cross-platform that
behave like Unix apps, not PS monstrosities.

[https://azure.microsoft.com/en-
us/documentation/articles/xpl...](https://azure.microsoft.com/en-
us/documentation/articles/xplat-cli-install/)

Powershell should be a _feature_ that draws people from AWS. Instead it is
seen as a drawback, even inside MS.

~~~
UK-AL
Simply stating something is bad, without anything to back it up, doesn't make
it bad.

Learn some alias's if you don't like the Get-X style of functions.

gal * | more

Will list tons of alias's for you.

~~~
tacos
Got a directory full of files with underscores in the names? Want spaces
instead? Easy, type this:

dir -recurse | where {-Not $_.PsIscontainer -AND $_.name -match "_"} | foreach
{ $New=$_.name.Replace("_"," ") Rename-Item -path $_.Fullname -newname $New
-passthru }

EDIT: I purposely posted the first Google result. You obviously Googled as
well as your code got it backward. But really, why isn't it this? It's worked
since the 1980s. You'll dig it since it uses extra apostrophes.

    
    
        rename '_' ' ' *

~~~
UK-AL
Dir | rni –NewName { $_.name –replace " ","_" }

That command does some extra stuff, which would make the bash equivalent also
complicated.

~~~
latkin
Yep. Technically the request included recursive rename, and to avoid renaming
directories, but gosh that's not hard:

    
    
        dir -rec -file | rni –newname { $_.name –replace "_"," " }
    

Edit: Oops, request did _not_ include recursive, the original sample solution
did.

FWIW top Google results for "unix recursively rename files" give below
solutions (slightly different scenarios but you get the idea). Not
particularly shorter, or less cryptic:

    
    
        find . -iname "*dbg*" -exec rename _dbg.txt .txt '{}' \;
    
        shopt -s globstar nullglob
        rename _dbg.txt .txt **/*dbg*

~~~
UK-AL
His 'rename' wasn't recursive.

<Quote>Y'all are still missing the point. We live in a world where people use
CoffeeScript to avoid typing a semicolon. When you Google a PowerShell problem
the Google results come back looking insane. You can play code golf here all
you want but even this version looks nuts to outsiders

It's a cultural problem. You don't solve it by shouting subtly-differing
versions of your culture, louder. ".</Quote>

You're not getting the point. Powershell is just short, and sometimes shorter
if you actually learn it.

"When you Google a PowerShell problem the Google results come back looking
insane" \- This is a problem with the age of powershell. Bash has been around
for ever, so there is lots of good quality content on the web.

------
CraigJPerry
Powershell and its long winded cmdlets are really hard for me to like. I
always fall back to cygwin on windows.

I once wrote a PS script to set some power management options on a corporate
laptop. The script was 11 lines long (vs 3 lines in Python), it was harder to
read and understand. Even with ISE available it was much harder to write.

I followed along with some exchange server tutorial where the prescribed easy
way to achieve the task was a completely unintuitive PS script. I kept
thinking about how much easier that particular config change was to make on a
Linux host running postfix.

I can't see what benefit PS has over cygwin bash but I'd love to hear ideas
because PS comes installed out of the box where I have to install cygwin
myself.

~~~
bitwize
PowerShell obeys the first iron law of I/O: ALL data has a type. Bash (and
Unix in general) -- does not.

Now of course the implementation of typed pipelines in PowerShell is clunky
and forced, because typed I/O primitives do not (yet) actually exist in
Windows, so all the piping is done within one process with streams of object
pointers, else it doesn't work. There are other problems, too: I recall one
advocate linking me to the PowerShit solution to some admin task like changing
the ACLs of a directory tree recursively. It involved including a C# program
as a herestring, passing it to the C# compiler, and loading the resulting
bytecode. The advocate said "Isn't this beautiful and elegant?"

But in principle the model embraced by PowerShell is _strictly_ more robust
than bash's fragile "dumb byte pipes" model.

"Get a byte, get a byte, get a byte, byte, byte!" \--NT architect Dave Cutler,
on Unix I/O

~~~
Someone1234
And the UNIX style has a cost: It is insecure e.g. [0][1].

Luckily modern UNIX-based systems are rarely used as multi-user terminals
these days or we would see many more privilege escalations via exploiting bugs
in scripts which iterate over user owned files. Even in web scenarios, most
web frameworks carefully manage what is allowed in a filename or set the
filename themselves.

Ultimately because on UNIX there is no type, you have to make assumptions.
These assumptions are sometimes dangerously wrong. You can definitely write
scripts and execute commands in a more secure way, but you can go google Linux
tutorials right now and find tons of examples where newbies are taught to do
it wrong out of the gate.

Data types make this "secure by default." String for everything requires the
script-writer or command line-writer to be perfect every time they hit return.

[0]
[http://www.defensecode.com/public/DefenseCode_Unix_WildCards...](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt)
[1] [https://www.helpnetsecurity.com/2014/06/27/exploiting-
wildca...](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-
linux/)

~~~
striking
Bash scripts aren't usually intended to be secure. They're quickly written
one-offs that do some tiny task and do it well, not usually exposed to an
insecure environment or externally controlled input.

If you want to write a good program, use a programming language that cares
about good programming. Bash et al. don't care about how good the program is,
they care about getting something done quick.

~~~
verbatim
Well, that's what we thought before the ShellShock vulnerability ended up
being a major security worry due to all of the places that bash scripts end up
being used.

~~~
striking
Bash doesn't come with a guarantee of usability sticker. Actually, it comes
with an indemnification of liability sticker.

People who are dumb enough to hammer in screws shouldn't be building houses.
Whether they do or not isn't exactly my worry.

Don't use the wrong tool for the job and you probably won't get burned.

------
rottyguy
>> Let's be honest. What many people think of as "the default Windows command
line", cmd.exe, is atrociously bad. Selection is awkward, resizing is hard,
the syntax is arcane, the list goes on. If you do nothing else, there are two
things you can do to make the basic, vanilla experience bearable.

Funny, from a guy coming from Windows to Unix I think the exact opposite. Each
command comes with a bazillion options and the defaults are simply atrocious
(to read the man, oy). Yes I understand that you can tailor each command in
some startup script but why? It almost feels like every command needs to be
created to solve 5 million things when 99% of the time you use it for 1 or 2
things. A few of my favorites:

Scripting:

A = 123 vs A= 123 vs A=123 should be the same!

Please use trim() in your program when parsing tokens!

Keyboard:

Please, for the love of god, make the keyboard behave like a keyboard. I don't
want to be logged into some terminal and have the Backspace not behave like a
backspace (^H??). Yes, I'm sure I can make it work via some, again,
configuration magic or enter emacs mode, but, again, why?

cd.. should just work.

</rant>

Having been on unix for the last 7mo after years of windows, I do like some
things but let's not be too quick to call the kettle black.

~~~
onli
> I don't want to be logged into some terminal and have the Backspace not
> behave like a backspace (^H??). Yes, I'm sure I can make it work via some,
> again, configuration magic or enter emacs mode, but, again, why?

You don't have to do any magic for that normally. Even if using just xterm
with bash, backspace should behave like backspace almost everywhere. You had
some weird configuration there – possible you used the terminal of a
greybeard?

~~~
wdmeldon
I think you're correct on this one. I ran into this issue once and it was some
silly, easily fixed issue. Sadly I don't remember what it was.

------
Pxtl
At our office we jokingly refer to powershell as "two googles per line" \- a
term coined by its strongest proponent at the company.

It thought it would come naturally over time, but it never does. It seems
needlessly cryptic and verbose in so many ways. I've started using LinqPad for
stuff I would normally do in cmd now.

~~~
UK-AL
Learning Bash is just as cryptic. At least powershell function names have
logic behind them.

~~~
Klathmon
I've only been working professionally with linux for 5-ish years, but i'd say
that i'm still at the "2 googles per command" number for bash.

Some of it stems from the fact that i just don't use it enough, but most of it
from the fact that this shit just isn't intuitive. why is -b the flag for key
length in ssh-keygen? Why is -v the flag for "don't include" in grep? I have
those memorized now, but there is no way they are "intuitive".

~~~
yoodenvranx
> Some of it stems from the fact that i just don't use it enough, but most of
> it from the fact that this shit just isn't intuitive.

I have exactly the same problem.

I use Linux since about 8 years but somehow I just don't use the commandline
very often so I forget stuff all the time. Because of this I have half a dozen
post-its glued to my monitor for all the grep/git/whatever tricks I just can't
keep in my head. And for other stuff I use about once a year I have a long
linux_tricks.txt on my desktop where I write down all the tricky and obscure
command line stuff.

~~~
Klathmon
Holy shit git!

I need to reset my git repo to match origin, is it git reset hard --HEAD or
git reset HEAD --hard?

I'm like 90% sure they switch it with every update.

~~~
scrollaway
It's just git reset --hard. HEAD is implied.

Edit: To be more specific:

    
    
        git  # the executable
        reset  # the operation
        --hard # the type of reset being done (hard reset)
        HEAD  # where to reset *to*. Defaults to HEAD if not specified.

------
hobs
I think a lot of the hate on powershell is that it chooses to do things very
similar to existing languages, but just different enough to confuse
practitioners of anything else.

Posh also suffers in its somewhat easy to invoke any .NET library, so people
start comparing it to a more tooled programming language or something with
more sane libraries, and the "ISE" is nowhere close to an IDE (why isnt
powershell a first class citizen in visual studio! yes I know there are tools,
they are not great.)

Nonetheless, after a few years of working in sql server I have adopted more
and more posh in my life because its simply the fastest way to get things done
if you are doing windows server management.

I usually find myself on one of these two places if I am looking for
something:

Mike Fal (SQL Server focus, he is great)
[http://www.mikefal.net/](http://www.mikefal.net/)

Hey Scripting Guy!
[https://blogs.technet.microsoft.com/heyscriptingguy/](https://blogs.technet.microsoft.com/heyscriptingguy/)

edit: forgot to mention that MSFT helped to cause problems by massive changing
how the language did things over time(usually for the better), so ps1 vs ps4
is crazy different, another reason to be annoyed because which version comes
with which product is a fun skew to deal with (thanks sqlps having ps2.0!)

------
Poiesis
I don't really care about "It's Just Text" vs "Data Typing FTW." There are
different tradeoffs at play here, and to my mind that's ok. I'm just thrilled
to have _something_ that's: \- Internally consistent \- Well documented \-
Available by default \- Full featured \- Still being improved

Sure, I'm not thrilled with having to learn another language to get anything
done. But it's so much better than what came before that I don't care.
Besides, Bash and friends certainly have their quirks as well.

------
gpvos
I tried both ConEmu (twice) and Console2 in the past, but both were too
unstable for regular use. If someone can convince me that the situation has
markedly improved, I might try again, but I guess I'll just wait until we
upgrade to Windows 10 at my workplace (which they say is any day now).

~~~
a3n
Happy ConEmu plus clink user for at least a year, I suspect more, but I don't
keep track, I just move on.

~~~
gpvos
Hmm, just installed clink 0.4.7 (with autorun disabled for now). "clink
autorun --help" consistently crashes. But at least it hasn't taken down the
console yet, so I guess I'll try it out for some time. It's really a nice
concept.

~~~
a3n
mmmrrrm, don't know, don't remember. I do know that when I start ConEmu, I
have to ctrl-alt-J to get command line features. So maybe I had trouble with
autorun too? Don't remember.

~~~
a3n

      > clink autorun --help
      Clink v0.4.4 [git:a60c0a] Copyright (c) 2014 Martin Ridgers
      http://mridgers.github.io/clink
      
        -i, --install         Installs an autorun entry for cmd.exe.
        -u, --uninstall       Uninstalls an autorun entry.
        -s, --show            Displays the current autorun settings.
        -v, --value <string>  Sets the autorun to <string>.
        -h, --help            Shows this help text.
        -- <args>             Pass <args> that follow '--' on to Clink.
    
      >clink autorun --show
      native : "C:\Program Files (x86)\clink\0.4.4\clink" inject --profile "~\clink"
       wow64 : "C:\Program Files (x86)\clink\0.4.4\clink" inject --profile "~\clink"

------
agumonkey
No mention of clink ? surprising, cmd.exe meets readline. Highest ROI 'update'
I know on Windows
[https://mridgers.github.io/clink/](https://mridgers.github.io/clink/)

~~~
a3n
ConEmu plus clink is my mitigation of choice.

Line oriented copy/paste, instead of cell oriented, is a big win.

~~~
latkin
In Win10 there is finally line-based copy/paste built-in. You can still get
block-based by holding Alt.

------
andkenneth
Most of my issues with windows command line have been solved by installing the
unix tools to the path when installing git. Provides most of the commands I
need (including a native ssh that works from the windows+r dialouge) and I
have mingw if I need to do something with bash itself.

This on windows 10 with it's nice new command window is pretty nice, but I
still do anything serious on my macbook.

------
SeanDav
> _" And, purely subjectively, I think the .ps1 syntax is a lot more readable
> than the old .bat syntax."_

The Author does say "subjectively" but in my experience, both personally and
with others, the reverse is true. Powershell can seem to be really cryptic.

~~~
sz4kerto
Bash can be _extremely_ cryptic as well, we just learned it over time. Look at
awk :)

~~~
typon
Why use bash when you can use Python with os and sys modules?

~~~
TallGuyShort
I prefer Python when appropriate, but if you're going to "shell out" a lot and
pipe a bunch of commands together it starts getting too verbose and loses it's
elegance. I agree with other posters that bash is not intuitive, but if you've
worked with it for a long time, there's nothing like being able to cat | grep
| sed in a one-liner, rather than creating a bunch of Process objects, etc.

~~~
typon
If you're doing cat, grep, sed I'd say that bash is very intuitive and I use
it for that purpose all the time. If you're writing bash scripts, with if
structures and loops and everything, then just python.

~~~
pritambaral
Perhaps an unpopular opinion, but I still prefer to stay in bash even when I
need loops and conditionals. If I'm already writing in Python, then sure,
Python it is. Or ruby, or js, or whatever I'm in. But when I'm in bash and I
can do it easily enough in bash, why complicate?

------
emodendroket
I guess it's heretical to say this in some circles but I really like
PowerShell, despite its faults. An object-oriented shell is a really good idea
that saves a lot of time trying to munge texts with regular expressions and
such.

That said the return semantics stink.

------
lolive
Git for Windows is bundled with Git-Bash. A very Linux-like commande line.
Works like a charm.

I also use MobaXTerm as my Putty replacement. It also comes with a Bash
terminal that works fine. Very handy!

(Two reasons why I love to have learnt Bash)

~~~
chombier
Git for Windows is probably the first thing I install as soon as I log into a
new Windows computer.

Granted, bash may not be the most intuitive shell ever, but it just works
about everywhere and this is a huge advantage when switching OS regularly.

------
maratc
> _One of the reasons you use Windows is so you don 't have to use the command
> line._

It's the other way around: One of the reasons I _don 't_ use Windows is
because I _have_ to use the command line.

------
ohitsdom
I develop on Windows and use cmd.exe daily (for simpler tasks like running
Gulp or PhantomJS). It's hard to overstate how much of an improvement Windows
10 brings to the command line. Keyboard cut and paste, resizing, better text
selection seem so wonderful. It's a crime it took Microsoft this long for
these simple features.

There's also other handy improvements, like typing "cmd" into the file
explorer location bar to open a command window to the current location you are
viewing.

~~~
breck
Yes! I joined Microsoft 2 years ago, prior to that was on OS X. I couldn't
believe how awful cmd.exe was. It was like if a college student half
implemented some homework assignment and we all had to use it. I tried using
cygwin, PowerShell, and other shells but that was hard because too much of my
day to day work depended on shared scripts that I would have to manually
update for my shell. So I was stuck with cmd.exe and it was miserable.

Windows 10 fixed that with the improvements you mentioned. It's still no
"Terminal", but it's now about 80% as good, instead of 1%.

------
bediger4000
_One of the reasons you use Windows is so you don 't have to use the command
line. But sometimes it's unavoidable—maybe you need to do some advanced git-
wrangling, or you're developing in an environment with CLI-based tools that
are far more mature than their GUI counterparts._

This viewpoint is just plain wrong. Since GUIs typically don't have a way of
doing sequences of commands other than clicking and waiting, then clicking
again, or of automatically making decisions, the biggest reason to use a CLI
would be to express things that you can't with a GUI - like anything that
requires a flow-of-control with if-then-else.

After all, that's one of the reasons that rebuses are fun - they're
indeterminate and it's fun to de-ambiguate them. It's less fun to have to do
all de-ambiguation yourself, when a simple pipeline or while-loop would do the
trick.

------
jug
I think Powershell is a huge leap beyond Command. I just wish scripting was
easier with it, speaking of its return values:
[http://stackoverflow.com/a/10288256/9744](http://stackoverflow.com/a/10288256/9744)

Maybe there are better programming patterns for me to use here. Coming from
traditional imperative languages, I was confused though, especially when I got
to nests of functions, return values, and debug outputs. I mean, I later
understood why things worked like they did -- I just had a hard time wrapping
my code around the philosophy. Which is unusual for me to have with a language
from Microsoft in their post-.NET era.

------
jupp0r
> I know what you're probably thinking. One of the reasons you use Windows is
> so you don't have to use the command line.

I know what I'm thinking. One of the reasons I don't use Windows is that its
command line is a second or third class citizen.

~~~
hodwik
Right. I don't understand how people get any real work done on a Windows
machine.

What should take 2 seconds to type takes 20 seconds to find in godawful menus,
that get harder and harder to find with each new version of Windows.

------
latkin
I did Windows dev exclusively for a long time, and was an early Powershell
adopter. Recently I switched companies and now I swap back and forth from
Win10 (PS v5) to OSX (Terminal). I'm massively more productive in Powershell,
mostly due to my inexperience with Unix. There are a few things I think I can
legitimately argue, though:

The power of the unix command line is mostly from the utility commands
themselves, not from the shell language/ecosystem. Nobody seems to be super
enthusiastic about bash as a language (see all of the "at this point I just go
to perl/python/etc" comments), but the commands themselves are super powerful
and flexible. If you put in the time to really learn the commands and their
flags, you can do quite a lot. Watching experienced unix users at the prompt,
I routinely think "oh nice, that's a great command to have", but rarely "oh
that's a handy language feature" or "wow Bash made that really easy".

With Powershell, it's kind of the opposite IMO. The language and ecosystem are
mostly well-thought-out, consistent, and powerful. Everything-is-typed,
pervasive and awesome tab-completion, mature pipeline system, decoupling of
data and how it's displayed, access to the .NET standard libs, ease of
extensibility and scripting (oh god it's so nice never neededing to parse
arguments!), reflective help system and discoverability features, easily
hostable in other apps... That all comes from the ecosystem. Where Powershell
often falls flat is the limited set of built-in commands, or the lack of
sensible flags/options for those commands which do exist. You're often falling
back to legacy cmd.exe-era executable utils, or invoking some .NET API, both
of which result in more verbose, awkward code. e.g. reading/writing the
registry is SUCH A PAIN with powershell builtins (why?!?!?), so reg.exe it is.
Much of that comes from Powershell's relative youth (the set of builtins and
their flags is still evolving), and the relative script-unfriendliness of
Windows as an OS compared to unix.

So for a particular action, in unix you have have a utility (or even N
utilities) with 15 arguments to handle 95% of possible cases, in Powershell
you'll get a cmdlet with maybe 5 or 6 arguments that handles 75% of cases, but
the output is an object so the remaining 25% can be done by calling some
method or grabbing a field. Both approaches have their strengths and
drawbacks. The Powershell approach tends to scale better, I'd say - you can
create fairly large scripts/packages in pure Powershell without needing to
bail out to Python or C#.

------
gr3yh47
>Upgrade to Windows 10... the benefits really can't be overstated.

except that there's tons of drawbacks to counteract said benefits. Privacy
notwithstanding, power-use has been fractured and the flow of configuration
ruined in 10

------
alimbada
I've been wanting bash style completion in a Windows Command Line for so long.
Big thanks to the author for the PSReadLine tip; it works perfectly in ConEmu
whereas Clink wouldn't work at all.

------
joewrong
[http://scoop.sh/](http://scoop.sh/) has been a nice-to-have tool, similar to
homebrew on osx

------
dolguldur
anybody tried cash [0] ?

[0] [https://github.com/dthree/cash](https://github.com/dthree/cash)

------
kuma4
I didn't expect there were a lot of people who knew well about PowerShell
here. I like PowerShell.

------
ezoe
I don't use Windows anymore so I don't care much. But, When does Windows offer
a terminal emulator with sane character encoding(UTF-8)?

This is 2016, CP932(Shift JIS with IBM extension) shall be abandoned.

------
tkubacki
Windows is no go for me as long as there will be no option to use ansible from
cmd - fortunately you can manage windows box from OSX or Linux box with
ansible

------
ekianjo
Why would you even want to make Windows command line better, instead of using
a state of the art command line of Linux via a VM running in Windows, if you
really cannot escape the Windows realm ?

~~~
DominoTree
Because a VM is overkill and won't allow you to interact with the Windows
host.

~~~
gutnor
Windows used to provide Interix which was a subsystem that allowed use to use
quite a bunch of posix utilities and offered quite a very good integration
with Windows. You could do quite a lot of things with it (we used it to
convert a unix app to windows in record time) and it was IMO superior to
Cygwin.

But that was 10 years ago, it disappeared at some point, being integrated
somewhere in either the server version or the professional edition (named
something like Unix Service for Windows) I lost track.

Considering all the work that MS is putting in interoperability those days,
I'm wondering if it will not make a come back at some point.

