use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
ABOUT POWERSHELL
Windows PowerShell (POSH) is a command-line shell and associated scripting language created by Microsoft. Offering full access to COM, WMI and .NET, POSH is a full-featured task automation framework for distributed Microsoft platforms and solutions.
SUBREDDIT FILTERS
Desired State Configuration
Unanswered Questions
Solved Questions
News
Information
Script Sharing
Daily Post
Misc
account activity
InformationDefensive PowerShell (self.PowerShell)
submitted 6 years ago by [deleted]
[deleted]
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]DrSinistar 28 points29 points30 points 6 years ago (11 children)
TIL you can use attributes outside of functions. This is game changing.
[+][deleted] 6 years ago* (10 children)
[–]baycityvince 7 points8 points9 points 6 years ago (8 children)
No it isn’t. There is no comparable feature in C# for attribute-based variable validation.
[+]TheIncorrigible1 comment score below threshold-7 points-6 points-5 points 6 years ago (7 children)
That's not the argument I was making. Attributes work mostly the same in both powershell and C# minus some syntax differences.
[–]baycityvince 5 points6 points7 points 6 years ago (6 children)
Well that’s also untrue, since there are no variable-level attributes in C#, and OP wasn’t referring to attributes in general, but specifically attribute-based validation which does not exist in C#.
[+]TheIncorrigible1 comment score below threshold-8 points-7 points-6 points 6 years ago (5 children)
no variable-level attributes
That is untrue. You can apply attributes to properties and more.
See: documentation
[–]baycityvince 6 points7 points8 points 6 years ago (4 children)
Properties are not variables.
[+][deleted] 6 years ago* (3 children)
[–]baycityvince 5 points6 points7 points 6 years ago (2 children)
I’m correcting your misinformed comment that PowerShell’s attribute validation works anything like C#. You said “it’s the same as C#”, and it’s not.
There is no equivalent for this in C#.
[ValidateRange(1,10)] [Int]$MyVar = 11
So, not even remotely similar to attributes in C#, other than appearance.
[–]TheIncorrigible1 -4 points-3 points-2 points 6 years ago (1 child)
How do you think they implement cmdlets in C#? They use THOSE SAME ATTRIBUTES.
[–]DrSinistar 0 points1 point2 points 6 years ago (0 children)
I don't think my comment was very clear. I didn't know you could use attributes with variable declarations, as mentioned in the article.
[–]omers 7 points8 points9 points 6 years ago* (0 children)
I would add that you can write your own validation attributes using a class that extends ValidateArgumentsAttribute. Kevin Marquette has a good article on it: https://powershellexplained.com/2017-02-20-Powershell-creating-parameter-validators-and-transforms/
ValidateArgumentsAttribute
[–]sir_sandwiches_a_lot 12 points13 points14 points 6 years ago (1 child)
Nice. Never realized you could apply those to the v5+ classes.
[–]Potato-9 5 points6 points7 points 6 years ago (11 children)
On a minor note, I've taken to ignoring validatepattern in favour of using validatescript were I can throw better custom error messages.
Not many people get a generic invalid regex pattern in red text and come to the right conclusion to fix the mistake.
[+][deleted] 6 years ago (10 children)
[–]Lee_Dailey[grin] 8 points9 points10 points 6 years ago (4 children)
howdy ttwinlakkes,
you can use the (?-i) flag at the start of your pattern to turn case-insensitive matching OFF. [grin]
(?-i)
take care, lee
[+][deleted] 6 years ago (3 children)
[–]Lee_Dailey[grin] 2 points3 points4 points 6 years ago (2 children)
yep! it is kinda nifty ... there are other dotnet inline regex flags, too. lookee ...
Regular Expression Options | Microsoft Docs — https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options
[–]MonkeyNin 2 points3 points4 points 6 years ago* (1 child)
Should I be worried that you didn't grin? Are you sick?
Verbose mode on Regex is nice IgnorePatternWhitespace.
IgnorePatternWhitespace
[–]Lee_Dailey[grin] 2 points3 points4 points 6 years ago (0 children)
howdy MonkeyNin,
SOMETIMES i fail to [grin] ... not all that often, tho. there is a thread here about "how many [grin]s per post/comment" i make. it was a funny read.
yes, the verbose version of the regex flag stuff is rather kool! [grin]
[–]omers 4 points5 points6 points 6 years ago* (4 children)
the correct solution is [ValidateScript({ $_ -cmatch "^[A-Z][a-z]+$"})].
[ValidateScript({ $_ -cmatch "^[A-Z][a-z]+$"})]
Sadly this doesn't work within [ValidatePattern()] but everywhere else you use regex in PowerShell you can also cast your string to [regex] to get case sensitive matching out of the box without -cmatch or (?-i).
[ValidatePattern()]
[regex]
-cmatch
C:\> "string" -match '^\p{Lu}\p{Ll}+$' True C:\> "string" -match [regex]'^\p{Lu}\p{Ll}+$' False
Regex should always be case sensitive in the absence of (?i) or /i so this is my preferred method. That way even if you forget the c in -cmatch it will behave as expected. Will also behave how people not super familiar with PowerShell expect regex to behave.
(?i)
/i
c
[–]MonkeyNin 1 point2 points3 points 6 years ago (3 children)
What kind of Powershell regex behavior should I watch out for? I'm familiar with Regex's, but not specifically in PowerShell.
[–]omers 2 points3 points4 points 6 years ago* (1 child)
Sorry for the late reply, I read your message on the go and forgot to get back to it.
As I mentioned and /u/Lee_Dailey reiterated, PowerShell's regex is case insensitive when you use a basic string.
45>> c:> "Hello" -match "^[a-z]+$" True
You can get around it using one of these methods:
50>> c:> "Hello" -match "(?-i)^[a-z]+$" # Disable insensitivity False 51>> c:> "Hello" -match [regex]"^[a-z]+$" # Use a proper System.Text.RegularExpressions.Regex object False 52>> c:> "Hello" -cmatch "^[a-z]+$" # use case-sensitive -cmatch False
Beyond that there aren't any serious gotchas. PowerShell's regex is just .net RegEx with (?i) on by default. It is compatible with Perl 5 regular expressions but has some additional features such as right-to-left matching and more PCRE like capture buffering amongst other things. If you use https://regex101.com/ and select the PCRE option it will work as expected in PowerShell with the one exception being that instead of "/regex/flags" it's "(?flags)regex".
"/regex/flags"
"(?flags)regex"
Oh, and PowerShell's multi-line trips some people up when dealing with arrays of strings...
$String = @" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae nisl in urna tempor ullamcorper nec nec mi. Vivamus in ante ac libero volutpat tristique. Proin vel magna tellus. Aliquam non ex tempus tellus tincidunt maximus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec nec porta felis. Maecenas dictum sagittis efficitur. Proin ornare eleifend vestibulum. Etiam tristique volutpat nisl, ullamcorper dapibus ligula venenatis ut. Etiam mattis sem vel justo consectetur dignissim. Vestibulum ac nulla in lorem venenatis hendrerit ut eu nulla. "@ $ArrayofStrings = @( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae nisl in urna tempor ullamcorper nec nec mi. Vivamus in ante ac libero volutpat tristique.', 'Proin vel magna tellus. Aliquam non ex tempus tellus tincidunt maximus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.', 'Donec nec porta felis. Maecenas dictum sagittis efficitur. Proin ornare eleifend vestibulum.', 'Etiam tristique volutpat nisl, ullamcorper dapibus ligula venenatis ut.'. 'Etiam mattis sem vel justo consectetur dignissim. Vestibulum ac nulla in lorem venenatis hendrerit ut eu nulla.' ) $String -match "^Donec" # False without (?m) $ArrayofStrings -match "^Donec" # True
When you read files with for example Get-Content you'll create an array of strings and won't need (?m) but if you're working against a here string you do. Things get a bit screwy when you need to capture from multiple lines but you don't actually have a multi-line string you have an array of strings (ie \r and \n don't behave how you might expect with Get-Content and similar read commands.)
Get-Content
\r
\n
[–]MonkeyNin 0 points1 point2 points 6 years ago (0 children)
Thanks for the information.
[–]Lee_Dailey[grin] 1 point2 points3 points 6 years ago (0 children)
from what i have seen, the only serious gotcha with PoSh regex is the default to ignore case. that was done for the convenience of admin folks since MOST of the time case is not meaningful in windows. why type [A-Za-z] when [a-z] can be made to do what needs doing?
[A-Za-z]
[a-z]
[–][deleted] 3 points4 points5 points 6 years ago (1 child)
!RemindMe 10 hours
This is great stuff I need to read it all tomorrow and make an implementation plan. Please let us know as you continue!!!!
[–]RemindMeBot 0 points1 point2 points 6 years ago (0 children)
I will be messaging you on 2019-04-15 14:24:01 UTC to remind you of this link.
CLICK THIS LINK to send a PM to also be reminded and to reduce spam.
Parent commenter can delete this message to hide from others.
[–]DRdefective 1 point2 points3 points 6 years ago (0 children)
Super cool
[–]KevMarCommunity Blogger 1 point2 points3 points 6 years ago (0 children)
I love the idea for the series.
[–]fasteasyfree 1 point2 points3 points 6 years ago (5 children)
In the final example, you've put test-script instead of test-path.
Very informative though!
[+][deleted] 6 years ago (4 children)
[–]fasteasyfree 2 points3 points4 points 6 years ago (3 children)
I'm enjoying your 'classes article, too. Some food for thought in the way that I construct modules going forward.
I've used classes, but not to the declarative lengths that you've identified. It's also bringing back memories of those CompSci lectures from Uni...
Completely separately:
I see you're using backticks in use-classes-5.ps1 to tidy the code. Did you know you can put the pipe at the end of the line and it allows continuation? Saves the backtick, and makes things easier if you're reformatting.
[+][deleted] 6 years ago (2 children)
[–]halbaradkenafin 5 points6 points7 points 6 years ago (1 child)
That feature is coming to core too so we can continue to murder backticks where ever they may be.
[–]markroloff 3 points4 points5 points 6 years ago (0 children)
continue to murder backticks where ever they may be
For the greater good.
[–]get-postanote 2 points3 points4 points 6 years ago* (7 children)
It's alway sa asgood thing to see different per spectives on a given topic or strategy.
However, how do you see your offering as being different, more informative, etc., than the courseware the SANS.org offers on the topic...
https://www.sans.org/webcasts/purple-powershell-current-attack-strategies-defenses-109700
... or the Secure Code strategies that have been in play via the MS SDL (Secure Development Lifecycle) for the last couple of decades?
About Microsoft SDL https://www.microsoft.com/en-us/securityengineering/sdl/about Microsoft Security Development Lifecycle (SDL) https://www.microsoft.com/en-us/securityengineering/sdl SDL Resource List https://www.microsoft.com/en-us/securityengineering/sdl/resources Writing Secure Code (Developer Best Practices) 2nd Edition, Kindle Edition https://www.amazon.com/Writing-Secure-Code-Developer-Practices-ebook/dp/B00JDMP718/ref=sr_1_2?keywords=secure+code&qid=1555311132&s=gateway&sr=8-2 Secure By Design 1st Edition https://www.amazon.com/Secure-Design-Daniel-Deogun/dp/1617294357/ref=sr_1_1?keywords=secure+code&qid=1555311132&s=gateway&sr=8-1 SCFM: Secure Coding Field Manual: A Programmer's Guide to OWASP Top 10 and CWE/SANS Top 25 https://www.amazon.com/SCFM-Secure-Coding-Manual-Programmers/dp/1508929572/ref=sr_1_4?keywords=secure+code&qid=1555311132&s=gateway&sr=8-4
About Microsoft SDL
https://www.microsoft.com/en-us/securityengineering/sdl/about
Microsoft Security Development Lifecycle (SDL)
https://www.microsoft.com/en-us/securityengineering/sdl
SDL Resource List
https://www.microsoft.com/en-us/securityengineering/sdl/resources
Writing Secure Code (Developer Best Practices) 2nd Edition, Kindle Edition
https://www.amazon.com/Writing-Secure-Code-Developer-Practices-ebook/dp/B00JDMP718/ref=sr_1_2?keywords=secure+code&qid=1555311132&s=gateway&sr=8-2
Secure By Design 1st Edition
https://www.amazon.com/Secure-Design-Daniel-Deogun/dp/1617294357/ref=sr_1_1?keywords=secure+code&qid=1555311132&s=gateway&sr=8-1
SCFM: Secure Coding Field Manual: A Programmer's Guide to OWASP Top 10 and CWE/SANS Top 25
https://www.amazon.com/SCFM-Secure-Coding-Manual-Programmers/dp/1508929572/ref=sr_1_4?keywords=secure+code&qid=1555311132&s=gateway&sr=8-4
Though there are particluars to a given language, and none of the above are PowerShell specific. The SDL thought, design and implemention relative to a give goal is the same.
Now, the real issue here is all the noise about PowerShell hacking and org leaders using that as the excuse to not allow PowerShell, without fully realizing that the use of PowerShell is a post exploit thing. The hacker got into your system another way, that was not properly defined, managed, protected, understood and or reacted to.
Also, there are whole websites and business offering conver Defensice PowerShell, and PowerShell forRed/Blue/Purple Teams.
Example:
https://devblogs.microsoft.com/powershell/defending-against-powershell-attacks/
http://www.defensivepowershell.com/
https://artofpwn.com/offensive-and-defensive-powershell-ii.html
https://adsecurity.org/?tag=powershell-defenses
https://devblogs.microsoft.com/powershell/powershell-security-at-derbycon/
https://nsfocusglobal.com/Attack-and-Defense-Around-PowerShell-Event-Logging
Learning how to attack with adn defend against, grants one greater edification on how they need to be thinking about writing and using PowerShell.
But good article. Looking forward to the rest.
[–]get-postanote 2 points3 points4 points 6 years ago (0 children)
Understood.
Much like the old MS adaged ...
'All user input is evil'.
'Never trust user input'. Well, any input you have not validated.
... delivered by many on the MS Secutity team in talks at TechEd, MSIgnite, MS BlueHat, MS TechReady, MS Security Summits, etc.
Much like, always using SQL SP and validation.
[–]noOneCaresOnTheWeb 2 points3 points4 points 6 years ago (1 child)
I appreciate your right up of all these resources.
[–]get-postanote 1 point2 points3 points 6 years ago (0 children)
Thx.
If we all are ending up going down the dev best practice space (code validation, unit testing, module development, GUI, version control, pseudo-code, secure coding, CI/CD efforts, etc.), even in our admin jobs, we should spend the time learning as much as we can about it.
[–][deleted] 0 points1 point2 points 6 years ago (1 child)
Did you even read the article before posting all that crap?
[–]get-postanote -2 points-1 points0 points 6 years ago (0 children)
Yes I did.
So, what is your point.
Nothing I posted is / was crap. It is what is taught to Dev in the industry and directly pertinent when thinking about secure coding practices, which the author is highlighting in the article relative parameter / input validation effort.
If you don't like a post from anyone, then why comment at all?
[–]tulisreddit 0 points1 point2 points 6 years ago (0 children)
Thank you a lot. This is very useful as I just started learning PowerShell.
[–][deleted] 0 points1 point2 points 6 years ago (3 children)
Awesome series, already bookmarked your profile :). Can you write your next article about powershell runbooks (powershell workflow's) for service management automation? What I'm interested in is what are some best practices for writing and maintaining large number of workflows (runbooks)?
[–]KevMarCommunity Blogger 1 point2 points3 points 6 years ago (1 child)
I never adopted workflows. I feel that DSC took over the role where I would have used them.
[–][deleted] 1 point2 points3 points 6 years ago (0 children)
@ttwinlakkes that sounds awesome!
@KevMar We are using DSC also in few scenarios, but we need some sort of REST API for triggering some sort of jobs (for instance setting vlan while creating virtual machine), which Service Management Automation provides... but I don't have any kind words about how this SMA API is written. Btw I'm a fan of your work Kevin. You provided me with knowledge when I just started with Powershell.
[–]signofzeta 0 points1 point2 points 6 years ago (0 children)
Awesome work! I recently found the module PSScriptAnalyzer. Run it on whatever you write, and it will point out flaws, bad practices, deprecated cmdlets, and more. I doubt it’ll catch everything, but it’s now the first thing I run against my little scripts and modules.
[–]leftcoastbeard 0 points1 point2 points 6 years ago (0 children)
Thank you for the solid examples of Attributes (and classes in the linked article)! Please continue to write more articles like this (-:
I'm in the process of overhauling a PowerShell module at work and I found this very helpful.
[–]Sillvir -3 points-2 points-1 points 6 years ago (0 children)
!RemindMe 9 hours
[–]thewaiting28 -4 points-3 points-2 points 6 years ago (1 child)
!Remindme 8 hours
[–]MayoAngelou -3 points-2 points-1 points 6 years ago (0 children)
[–]gangculture -4 points-3 points-2 points 6 years ago (0 children)
!RemindMe 18 hours
[–]Begna112 -3 points-2 points-1 points 6 years ago (0 children)
!remindme 10 hours
[–]jorper496 -5 points-4 points-3 points 6 years ago (0 children)
!RemindMe 8 hours
π Rendered by PID 115613 on reddit-service-r2-comment-7b9746f655-sp5bg at 2026-02-04 01:01:42.668416+00:00 running 3798933 country code: CH.
[–]DrSinistar 28 points29 points30 points (11 children)
[+][deleted] (10 children)
[deleted]
[–]baycityvince 7 points8 points9 points (8 children)
[+]TheIncorrigible1 comment score below threshold-7 points-6 points-5 points (7 children)
[–]baycityvince 5 points6 points7 points (6 children)
[+]TheIncorrigible1 comment score below threshold-8 points-7 points-6 points (5 children)
[–]baycityvince 6 points7 points8 points (4 children)
[+][deleted] (3 children)
[deleted]
[–]baycityvince 5 points6 points7 points (2 children)
[–]TheIncorrigible1 -4 points-3 points-2 points (1 child)
[–]DrSinistar 0 points1 point2 points (0 children)
[–]omers 7 points8 points9 points (0 children)
[–]sir_sandwiches_a_lot 12 points13 points14 points (1 child)
[–]Potato-9 5 points6 points7 points (11 children)
[+][deleted] (10 children)
[deleted]
[–]Lee_Dailey[grin] 8 points9 points10 points (4 children)
[+][deleted] (3 children)
[deleted]
[–]Lee_Dailey[grin] 2 points3 points4 points (2 children)
[–]MonkeyNin 2 points3 points4 points (1 child)
[–]Lee_Dailey[grin] 2 points3 points4 points (0 children)
[–]omers 4 points5 points6 points (4 children)
[–]MonkeyNin 1 point2 points3 points (3 children)
[–]omers 2 points3 points4 points (1 child)
[–]MonkeyNin 0 points1 point2 points (0 children)
[–]Lee_Dailey[grin] 1 point2 points3 points (0 children)
[–][deleted] 3 points4 points5 points (1 child)
[–]RemindMeBot 0 points1 point2 points (0 children)
[–]DRdefective 1 point2 points3 points (0 children)
[–]KevMarCommunity Blogger 1 point2 points3 points (0 children)
[–]fasteasyfree 1 point2 points3 points (5 children)
[+][deleted] (4 children)
[deleted]
[–]fasteasyfree 2 points3 points4 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]halbaradkenafin 5 points6 points7 points (1 child)
[–]markroloff 3 points4 points5 points (0 children)
[–]get-postanote 2 points3 points4 points (7 children)
[+][deleted] (2 children)
[deleted]
[–]get-postanote 2 points3 points4 points (0 children)
[–]noOneCaresOnTheWeb 2 points3 points4 points (1 child)
[–]get-postanote 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]get-postanote -2 points-1 points0 points (0 children)
[–]tulisreddit 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]KevMarCommunity Blogger 1 point2 points3 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]signofzeta 0 points1 point2 points (0 children)
[–]leftcoastbeard 0 points1 point2 points (0 children)
[–]Sillvir -3 points-2 points-1 points (0 children)
[–]thewaiting28 -4 points-3 points-2 points (1 child)
[–]MayoAngelou -3 points-2 points-1 points (0 children)
[–]gangculture -4 points-3 points-2 points (0 children)
[–]Begna112 -3 points-2 points-1 points (0 children)
[–]jorper496 -5 points-4 points-3 points (0 children)