86 points · by selmat · 9y ago · 116 comments
I understand that this is done for security reasons, but Windows already lets you execute any executable or BAT file that you might have downloaded from the Internet. So I'm not sure that disabling PowerShell script execution really gains you much (and there are probably other better solutions anyway).
So IMHO as long as DOS is available and PowerShell is so limited by default BAT files will not go away, which is unfortunate.
But what's the alternative? What's the proper way of signing a script, and how much work is it to do that?
https://gallery.technet.microsoft.com/PS2EXE-Convert-PowerSh...
Read more on how to use it at https://redmondmag.com/articles/2017/01/27/convert-a-powersh...
To sign a script you run:
Set-AuthenticodeSignature foo.ps1 $someCert
and make sure that $someCert 's pubkey is available on every user's computer.The alternative is of course to get every user to run `Set-ExecutionPolicy Unrestricted` to solve the "problem" permanently.
Disclaimer: I'm a PM on PowerShell at Microsoft, and the following is based on my personal observations. There's also no current plan to do any of what I suggested (but it's certainly giving me a lot to think about at the start of my work week).
The default ExecutionPolicy was engrained and controversial long before I joined the PowerShell Team (or even Microsoft), and I'll be the first to admit that, as a long time Linux user, I didn't GET why I couldn't just run arbitrary scripts.
The public Microsoft opinion on the matter has always been that ExecutionPolicy is there to try and prevent yourself from shooting yourself in the foot. In Linux, this is very similar to adding a +x to a script (although that's clearly much simpler than signing a script).
I'd say it's also akin to the red browser pages warning you about self signed certificates, or Microsoft/Apple "preventing" you from running certain app packages that are "untrusted" in one form or another. In one sense, you could actually argue that PowerShell was ahead of the curve.
Now as a power user with much less at a stake than, say, an IT administrator at a Fortune 500 company, the first thing I do with all these restrictions, warnings, and confirmation prompts is to turn them off.
But those warnings (often with no clear way to disable them) are there for a reason. PowerShell was built at a time when Microsoft admins were GUI heavy, and PowerShell did its best to herald them into a scripting world while fostering best practices. And if you're using a bunch of scripts sourced from SMB shares within your domain as a domain administrator, you don't want to accidentally run a script that hadn't gone through your internal validation process (hopefully culminating in the script getting signed by your domain CA).
So let me assume that you agree with everything so far. Why does this experience still stink? Any Microsoft administration worth their salt uses PowerShell, and many of even the power-est of users finds ExecutionPolicy annoying.
In my opinion, it's too hard to sign scripts. We should be following in the footsteps of the drive to get everything on HTTPS (props to Let's Encrypt and HTTPS Everywhere, along with many others). We should have guidance on signing if you have a CA, we should have guidance on getting scripts signed by third party CAs, and we should probably offer a cheap/free service for signing stuff that goes up on the PowerShell Gallery.
Oh, and we should make it easier to read the red error that gets thrown explaining how to lookup a help topic that tells you how to bypass/change ExecutionPolicy.
Unfortunately, that's all easier said than done. But the default being what it is puts the onus on us to do something to make security easier.
I understand your reasoning. I like some of your proposals. For example I'm all for making it easier to sign scripts, for example. Yet I feel that the possible solutions that you mention ignore the fact that you can bypass this "security" mechanism can be bypassed with a simple BAT file.
Why do PowerShell scripts require more security than a BAT file or an executable? Are users really safer thanks to the ExecutionPolicy check? Or are they simply worse off because people will either use less powerful BAT files or completelly opaque executables? At least with a PowerShell script you are able to inspect the code if you are so inclined. By pushing people to use executables instead they are less likely to know what changes will be done to the system.
If the problem is admins accidentally double clicking on unsigned scripts, by all means show a confirmation dialog (if the script is not signed) when a non signed script is _first_ executed. Actually, do that for BAT files and perhaps even for executables as well. But don't do it (by default at least) when someone calls a script explicitly from a command line or from another script. IMHO that would really make us all safer and would make PowerShell a real replacement for BAT files.
The use of PowerShell is completely analogous to using shell scripts on linux, along with making use of things like the GNU core utils and other nearly universally-installed utilities (curl/wget, tar, etc).
Traditionally there wasn't a lot you could do purely from a shell or scripting environment on Windows -- all the "good stuff" was in Win32 APIs, hence needing to ship binaries.
Microsoft has been adding everything to PowerShell, to the point that you can now do nearly anything you can do with the GUI -- and in many cases more, since most of the administrative commands accept a -ComputerName parameter and are integrated with domain authentication. It's only natural to take advantage of that.
I think this is a reasonable precaution, given PowerShell's potential scope as an attack surface, compared to the tiny fraction of Windows machines that are ever actually used to do anything with PowerShell.
Unfortunately Microsoft has let the genie out of the bottle, and most of the advancements in PowerShell security are centered around trying to add ACLs and logging to a scripting language, or figuring out how much of it you can disable and still have things work in production.
One of the best things we can hope to do going forward is sign on more Antivirus vendors to support Microsoft AMSI [1] which is basically a hook to pass PowerShell (and other scripting languages) off to your AV engine before they get executed.
1. https://msdn.microsoft.com/en-us/library/windows/desktop/dn8...
PowerShell has no more rights or power than the user it runs as. Anything you can do in PowerShell you could also do via WMI, Win32 API calls, etc.
Yes you are, any competent Windows admin that needs to do things will probably be using PowerShell to do said things.
And if you worked in that niche before PowerShell existed, you probably saw similar prevalence in PE/COFF use. Is it fair to say Microsoft "let the genie out" by allowing users of its operating system run software on it?
I went from having no knowledge at all to having written a web scraping function and checked 7000 sites for a specific phrase in less than two hours. It was the most intuitive piece of technology I've ever used.
If you're thinking "but... it's all so obvious. What is this guy talking about", ask yourself how long ago you first typed a shell command. Can you even remember how hard it was to learn? For me it was something like 15 years and I actually can remember because it made such an impression on me how terrible a system it was. (That and X86Config if you remember that insanity.)
Even though it was awful to learn, it feels totally easy and 'intuitive' to me now. But that's just because I use it so much. It's not intuitive. Don't fall into the old curmudgeon trap of thinking the thing that you find trivial through experience is actually good.
/rant
I can remember when I first learned bash/sh and Unix systems in general (by reading a book) and it was not really hard. However, I saw your sentiment a lot among the students I used to teach, and my response has always been "you're approaching it the wrong way." Bash, PowerShell, etc. are effectively programming languages, and my advice for learning programming languages applies: it's a language.
To elucidate, programming languages have their own vocabulary and rules just like a human language (and often, the rules are far more consistent and the vocabulary smaller) --- to ask questions like "Why not `list`?" is like asking "Why is the plural of sheep, sheep? Why is it called a mouton in French? Why not sheepe?"
Of course, you can ask such etymological questions when learning about programming languages and use them to help you, because they will have far more logical answers than the same questions about human languages; but in general, learning a language as a language is the best way to progress.
In fact I'd say super-verbose and somewhat convoluted languages like PowerShell (and C#, which I don't fancy much either --- nor its Java-ish ancestry, for that matter) may only appear to be more intuitive at first, but are actually hiding some quite nonintuitive complexity. The verboseness may make it easier to get started, but becomes a hindrance thereafter.
/rant
From what I recall, it was easy. Other than a few small differences ("mkdir" instead of "md", needs a space between the "cd" and the "..", and so on), it was similar to what I used every day. The rest I learned gradually, by reading shell scripts written by other people, and the man and info pages.
As for XF86Config, I always used the XF86Config generators which came with the distributions, so it was never much of a problem for me.
mv and ls are not shell commands, they are programs. They existed long before bash and were developed at a time of 110 baud teletype connections when short, highly abbreviated command names were worth the inconvenience.
If you don't like them you're free to alias "rename" to "mv" and "list" to "ls"
It redirects standard error to standard out? That's what it does in powershell anyway. Frex, I got this line in my $PROFILE:
$p2 = & $env:Python_2/python.exe --version 2>&1
To get the current Python 2 version on my machine. I'm not really sure what it's an alias for, but I like having the shortcut of the more concise syntax.The real problem is that, for some reason, python.exe --version outputs to standard _error_. That, I don't really get. I'm sure there's a good reason for it but it's not obvious and that's what's making the "2>&1" at the end hard to figure out.
Also, there's a story behind all these commands, their naming, the symbols, reasons for the brevity. But I've never not found Unix intuitive, even before I was aware of the reasoning behind everything. That said, Unix is definitely an environment for the more savvy. But what's intuitive for me is not necessarily intuitive for someone less savvy.
done?
There's a bunch of 3rd-party modules out there that do a great job of offering parallelism[1][2][3], and we also support the notion of "PowerShell Jobs"[4] (which one or two of those third-party implementations actually build on to achieve what they're doing).
However, we decided that strong parallelism support is important enough to build into the language, so we're mulling on a first-party design.
If you're interested, we've got an RFC out where we're looking for feedback on the parallelism/concurrency design.[5]
[1]: https://www.powershellgallery.com/packages/PSParallel/
[2]: https://www.powershellgallery.com/packages/SplitPipeline
[3]: https://github.com/RamblingCookieMonster/Invoke-Parallel
[4]: https://msdn.microsoft.com/en-us/powershell/reference/5.1/mi...
I miss-remembered the number of sited scraped but it's all the same. There is no parallelism (I really really am a complete non-techie) but actually in this case I didn't want to hammer away as the sites were all under the same domain and I imagine there might be trouble (which I why I also played it very safe and added the pause).
I know there are better and smarter ways of doing things and I did further modifications and experiments after my thread, but in any case, I had a task and was able to quickly complete it in PowerShell starting from absolute 0.
I've come to the conclusion that its just better to write a small c# app than try and use powershell
Similarly, we're trying to make some improvements to debugging right now with PowerShell 6.0 [1] (the one that's cross-plat and built on .NET Core), and I'm very interested in hearing your feedback on how we can do a better job there.
Even if it's "fix your docs" or "too hard to learn", that's great info, especially coming from a C# guru.
[1]: https://github.com/powershell/powershell/issues?utf8=%E2%9C%...
Try getting an experienced C# developer to write a PS function that:
- Initializes an IDisposable resource and deterministically disposes of it when the function terminates (successfully, with an error, or due to ctrl+C). - Honors the caller's $ErrorActionPreference/-ErrorAction. - Understands that catches won't catch "non-terminating" errors. - Throws errors without trashing the ErrorRecord so that the caller gets a meaningful stacktrace. - Copes with the difference between process working directory and PS working directory if a .NET method and a relative path are involved. - Doesn't blow up on a square bracket because someone didn't realize they needed -LiteralPath. - Doesn't accidentally write an unintended object to the pipeline. - Does something reasonable with pipeline input. - Doesn't get tripped up by type coercion magic - $a = @(); $a -eq $null - Uses multiple ParameterSets without creating ambiguity problems. - Doesn't get tripped up by PS silently swallowing exceptions thrown by property getters. - Uses some appropriate subset of language features and modules available across different versions of the OS and WMF. The OS based limitations are understandable. The hard dependencies that Microsoft's own products have on specific PS versions are not. - Is not super-slow.
It's not impossible, but it sure is hard (and takes a ton of boilerplate), and there aren't many resources out there to teach you how. It's all quick and dirty "how to do X" recipes for sysadmins that don't care about more than what they need to paste into a console.
To be clear, I actually mostly like PS I'm just trying to express a set of pain points here.
In 2007 I joined the powershell enthusiasts excited by the notion of a bash-like capability treating .NET constructs as a first-class citizen. I invested time into learning common use cases. Certain things you would THINK would be easy like loading a DLL as well as it's corresponding config file were actually quite difficult in practice which was a shame because the primary vision for powershell was to be flexible glue between compiled assemblies. Have you ever tried to invoke ms-test with powershell on a DLL which has a config xml?
I had a touch-and-go relationship with poweshell. I returned to use it a few years later to find that many of my powershell V1 scripts were obseleted by the powershell V2 runtime. Writing C#/.NET code to execute on many versions of windows this is rarely an issue. Writing powershell code to execute on many versions of windows you have a serious problem on your hands as the commands syntax and general practices vary significantly between versions.
To this day googling for examples on how to accomplish something basic such as running a dos command line call with parameters constructed within powershell is not only highly vexing for the occasional casual user such as myself but many of the answers I see in blogs or stackoverflow are completely temporal and you need to be careful to look for results dating around 2013 for powershell v2 because anything before that wont work, but not too new because v4 has a new approach and that would require a service pack not all my users can currently procure. Not to mention everyone writes powershell in a different style. You often end up with a handful of different code examples that look wildly different each with their own issues as well.
Sure there are expert powershell users out there with muscle memory that can write elegant solutions for version incompatibility issues and common gotchas, however for the casual seldom user the overall experience that too much frustration, less than intuitive approach and 10 ways to solve a common problem. It feels sort of like running perl in a dos prompt that is constantly changing. Compare this with zen of python where [There should be one-- and preferably only one --obvious way to do it.] I find myself installing python runtime and avoiding powershell when I'm required to make something of significant complexity and high compatibility.
* Referencing dependencies (if you're used to "add reference" and "using" it's awkward having to write a bunch of Assembly.Load that then needs to be maintained redundantly with the C#; it would be nice if PS could somehow work with VS/MSBuild projects)
* Calling extension methods (ties in with above since in C# they depend on "using")
* Calling generic methods
* Calling overloaded methods
* Calling async methods
There are workarounds for all the above but put together they definitely make PS less pleasant/useful for me.
Also, much of the above also applies to interop with WinRT which I think is becoming important (as much of the value of PS comes from good access to the underlying system, and more and more Windows functionality is being exposed through WinRT APIs).
The other problem I've had is performance - for example, PS could be useful for some of the same text processing tasks for which Bash is often used (and I'd prefer it for its stronger programming language/object system), but in my experience is dramatically and prohibitively slower when dealing with large amounts of text.
If PowerShell could support this, it would allow fully automated cert replacement for those of us who use Let's Encrypt on Windows (ducks)
It doesn't seem that I can currently debug scripts that are contained in a module folder, but not directly the script being called.
If I have a module file that looks like this:
Get-ChildItem -Path $PSScriptRoot\.ps1 | ForEach-Object{ .$_.FullName } # source the script files Export-ModuleMember -function -* # export those sourced scripts
I am not sure how it works exactly, but if I am writing a new cmdlet, Get-HackerNews.ps1, the breakpoints aren't hit in ISE. It would be super cool if it did.
------
Also is there guidance on module structure? Right now it looks like the docs indicate that all the cmdlets should be placed in the .psm1 file, but to me that sounds like it would get rather unmaintainable very quickly. Just looking at the one my dev team has created, we have nearly 50 exported functions. Maybe our our module could be broken up, but that would still leave us ~10 cmdlets per module.
- One which stops IIS app pools before a deployment (30 of them). I wanted to stop them all in parallel but found this far more difficult than executing a list of Tasks in c#. So I now just run c# console app to do it
- one which runs msdeploy commands against a web server and had many issues dealing with passing parameters down to msdeploy. I can't quite recall but I think it was either quotes or spaces related.
The ISE as it's called is very very basic. Not what I'd expect from MS. I'd like a full debugger.
There also seems to be a potential security risk of having editable text file scripts on a server Vs a compiled exe.
Compared to what cygwin’s bash does, it’s like an entirely different world.
1) Powershell mingles "process stdout" and "function return" to be one and the same. While this kind of makes sense, unless I'm extremely fastidious about redirecting everything I call to $null, chances are I'm not returning what I expect to return. The end result is I shy away from doing anything that needs to return values (rather than output) in Powershell, which is kind of important for anything nontrivial. I tend to set globals like I've gone back to the Apple 2 and started programming in BASIC again as a result, which gets messy real quick. Processing stdout/stderr in C# is a little annoying by comparison, but easily fixed.
2) Syntax changes in updates. When I installed powershell tools for VS, my scripts broke - to fix them I had to replace e.g.:
info "$vmGuid: has BuildMatrix tags: $tags"
With: info "${vmGuid}: has BuildMatrix tags: $tags"
And: logCmd {& $VBM -- clonevm $OriginalVmGuid --register --name $NewCloneId}
logCmd {& $VBM -- modifyvm $NewCloneId --natpf1 "ssh,tcp,$SshHost,$SshPort,,22"}
logCmd {& $VBM -- startvm $NewCloneId --type headless}
waitUpTo 60 3 -Sensitive $true {& $VBM -- guestcontrol $NewCloneId run --exe "/bin/sh" --username "$Username" --password "$Password" -- '/bin/sh' -c "mkdir ~/.ssh; echo '$PubKey' >> ~/.ssh/authorized_keys"}
waitUpTo 60 3 {& $Ssh -- -o NoHostAuthenticationForLocalhost=yes -o ConnectTimeout=60 -o BatchMode=yes -p $SshPort $Username@$SshHost -- '/bin/sh' -c "echo Server ready" 2>&1}
With: logCmd {& $VBM clonevm $OriginalVmGuid --register --name $NewCloneId}
logCmd {& $VBM modifyvm $NewCloneId --natpf1 "ssh,tcp,$SshHost,$SshPort,,22"}
logCmd {& $VBM startvm $NewCloneId --type headless}
waitUpTo 60 3 -Sensitive $true {& $VBM guestcontrol $NewCloneId run --exe "/bin/sh" --username "$Username" --password "$Password" -- '/bin/sh' -c "mkdir ~/.ssh; echo '$PubKey' >> ~/.ssh/authorized_keys"}
waitUpTo 60 3 {& $Ssh -o NoHostAuthenticationForLocalhost=yes -o ConnectTimeout=60 -o BatchMode=yes -p $SshPort $Username@$SshHost -- '/bin/sh' -c "echo Server ready" 2>&1}
Those "--"s I removed were mandatory in PowerShell 2 for at least some of these commands, yet caused problems in later versions - I don't even know how to write this in a way that will work on multiple powershell versions. I guess I have to explicitly pin -Version when invoking PowerShell all the time? The now simple problem of "How do I get this running consistently on multiple computers" has now turned into an IT and debugging headache. Meanwhile, C# projects get consistently built with a single VS and C# compiler version, and machines I install to are just running the even more stable bytecode.3) Default installs lag way behind - e.g. Windows 7 only comes with PowerShell 2 by default, so you don't even have things like Invoke-WebRequest, forcing you to write your own or get your IT department to install an updated version for everyone. C# just feels like it has more "batteries included" even for older .NET targets.
4) Figuring out exactly what types are expected vs what I happen to be using is a general muddle in Powershell for any sort of collection in my experience. C#'s static typing, clear errors, and intellisense in general is just extremely hard to beat.
But the worst thing I came across with Powershell is this. The fricking return semantics. http://stackoverflow.com/questions/10286164/function-return-...
PowerShell isn't 10x harder to use than C#, how do I know that? Because many people use PowerShell regularly in their day to day jobs, and do so quite successfully. Most people who actually use PowerShell don't complain about how hard it is.
It is harder than C# to debug, probably more than twice as hard, actually. Does that make it impossible to program in? Hardly. There are tons of other languages that are roughly equally difficult to debug, especially many of the dynamic languages: PHP, Python, etc. People have been building things of tremendous value with hard to debug languages for ages. The fact that C# has such a good debugging story is great, but it's not the end-all be-all of a language. Also, PowerShell has some significantly advanced debugging tools compared to a lot of other dynamic languages.
I can say that every programming language that I grew to love, I liked almost immediately. The ones that make no sense from the get-go, I don't spend much time on.
The whole "I can run this script on 100 different machines at once super easy" is fine, but lets see you try to write some rigorous code in PS and the come back and tell me how it's easier than C#.
They both have their place.
they definitely should have gone with some variation of C#.
There are crossover points (varying by person) where a scripting language is preferable to a shell, and where a strongly-typed language is preferable to a dynamically-typed language.
Especially the fact that I was able to accomplish what I set out to do in a very reasonable amount of time.
$sites = @('https://www.google.com/', 'https://www.example.com/')
$searchString = 'oogle'
$sites | %{ if ((iwr $_).Content -like "*$searchString*") { "$_;OK" } else { "$_;NOT OK" } } > C:\temp\output.csvSecurity issues aside, it's by far the best OS shell scripting language around, and it has concepts that make it different from any other attempt to write a shell language that includes pipes and redirections.
Admittedly not the best way to get at them, but Symantec's own website doesn't seem to list them in a more user-friendly fashion than straight up Googling...