r/PowerShell • u/feodorfff • Apr 30 '21
r/PowerShell • u/Sunsparc • Feb 21 '20
Misc Powershell 7's parallel ForEach-Object is mind blowing.
I just installed v7 yesterday and have been putting it through the paces to see what I can use it for by overhauling some scripts that I've written in v5.1.
For my company's IAM campaign creation, I have a script that gets a list of all users in the company, then has to look up their manager. This normally takes roughly 13 minutes for ~600 users if I run it from my computer, 10 if I run it from a server in the data center.
I adapted the same script to take advantage of ForEach-Object -ThrottleLimit 5 -Parallel and it absolutely smokes the old method. Average run time over several tests was 1 minute 5 seconds.
Those that have upgraded, what are some other neat tricks exclusive to v7 that I can play with?
Edit: So apparently the parallel handles my horribly inefficient script better than a plain old foreach-object in 5.1 and optimizing the script would be better off in the long run.
r/PowerShell • u/adbertram • Jul 22 '19
PowerShell Tutorial Mini-Course (Free) - A 9,000 word tutorial on PowerShell Toolmaking
r/PowerShell • u/Sharp_Eyed_Bot • Dec 18 '18
Script Sharing My Collection of Scripts That Help With SysAdmin Tasks
r/PowerShell • u/Ckarini • Jul 07 '19
Tutorial on creating Powershell applications using Visual Studio
r/PowerShell • u/nepronen • Feb 11 '18
News Poshgui.com Major update: Free online Gui Designer, Cmdlet builder, IDE, repository and more!
r/PowerShell • u/Federal_Ad2455 • Jun 13 '21
Script Sharing New blog post: Audit your Active Directory user passwords against haveibeenpwned.com safely using PowerShell
Maybe you will be surprised how many of your users use them as I was :D
r/PowerShell • u/ThomasMaurerCH • Apr 14 '21
Misc Stop typing PowerShell credentials in demos using PowerShell SecretManagement
r/PowerShell • u/FarsideSC • Dec 18 '18
Script Sharing WPF GUIs for Beginners
This is an absolute beginners guide to creating GUIs. Sources for information and visuals are linked as they appear.
So you want to create a GUI in Powershell, but you don't have a lot of experience with Powershell or with WPF. No sweat! At the start of 2017, I, myself, was really interested in GUI creation, but didn't really understand where to begin or what I was doing. I started out just copy/pasting code. Whenever I'd explain what my script was doing, I'd gloss over most of it as, "It just works and does this." Hopefully I can bridge a lot of those gaps in information or rephrase it to help you get past any roadblocks.
Although GUIs can do a lot to assist the target user, the trade off is that there is a lot that goes into keeping your GUIs looking presentable and functional. This is not an example of a GUI I'd present to my customers! However, this ought to be enough to get you started.
Note: Please feel free to ask questions. Although I don't claim to be an "expert", I am a wealth of knowledge on what doesn't work. I was self-taught, which comes with all due problems, troubleshooting, and facepalms.
Getting Started With Visual Studio
Install Visual Studio, NOT Visual Studio Code.
On the installation options, make sure the box ".Net desktop development" is checked.
Open up Visual Studio and create a new C# WPF App :: Image Source and Thread
Great! Now that we have a simple GUI, you can start changing the world! Well, not really. There isn't anything there except a blank window. So, let's create a TextBox from the Common WPF Controls from the leftpane of the Window. Just drag and drop the control onto your form. This creates a generic text box with no name. In order to interface with this object, let's give it a name!
Click on the TextBox. The Properties view should open up on the right portion of the screen. Change the "Name" to "tbUsername" and under the Common section, change the Text to "Username".
The XAML is automatically updated with our changes. This is the best part about Visual Studio- not having to write XAML. But there's one thing we ought to do more for the sake of it- and that's flip the colors of the foreground and background. So, under the Brush tab on the Properties Pane, click on Background. In the text box next to the color picker (should say #FFFFFFFF), type in "Black". This will set your background to black. Repeat the same steps for the foreground, but set that to White, or Green, or Red. In fact, you can call all of these colors and probably more.
Let's continue with our form: Let's repeat the previous process and create the following
PasswordBox: Name it pbPassword.
Place this control under the TextBox.
Set the Width to 20 and the Height to 23, then stretch out your password box to match the width of your TextBox.
In the Appearance Properties, Next to the Effects field, click on the "New" button and give it a drop shadow. Take note of the updated XAML.
Button: Name it bSubmit (lowercase b is not a standard prefix for buttons, I know, but I'm stubborn).
Set the Content (button text) to "Submit".
Place this under the PasswordBox.
Label: Name it lLabel
Place this above the TextBox.
Delete the text from Content.
What are we doing? We're modifying properties of these controls. The fields in the Properties view are the properties that each control can have set. This includes the Content or Text, Background and Foreground, what kind of font you're using, a seemingly unending list of visual effects, and more. For instance, one of my favorite to set is the TabIndex.
Event Listeners
Be sure to check your XAML for event listeners!
Here's a list common event listeners per control:
TextBox: TextChanged="tbUsername_TextChanged"
Button: bSubmit="bSubmit_Click"
ListBox (named lbList): SelectionChanged="lbList_SelectionChanged"
ComboBox (named cbItems): SelectionChanged="cbItems_SelectionChanged"
These parameters are meant for corresponding C# or VB.Net code, which is generated upon double clicking any of these controls. Visual Studio will automatically generate the most comment event listener for the respective control. (Thanks for helping!)
To fix errors generated by Event Listeners, simply remove the respective parameter (shown above) in the control's XAML.
Powershell ISE
Before we open up Powershell, copy all the XAML from Visual Studio. (CTRL + A --> CTRL + C)
Open up Powershell ISE (Start Button or Windows Key --> "Powershell ISE")
If you have one big blue console area, click on these buttons until your screen is oriented like this
In the white scripting area of Powershell, paste your XAML. It should look like this.
Save your document (CTRL + S) with the name "gui.xaml"
After changing the extension of the file to .xaml, notice how the colors changed in the scripting pane?
200 IQ Code in Action (at least I'd like to think so)
(Backstory and Credit) When I started out, I stumbled upon FoxDeploy, /u/1RedOne. Since then, he's made a lot of improvements to the original, already amazing, script areas that translate our GUI objects into Powershell objects. We will be borrowing some of this code, and taking out the parts that I don't personally use.
Create a new script in Powershell ISE by typing CTRL + N.
Copy and paste this section from here.
Save the document as xaml.ps1 (I usually do this for my own sanity)
In /u/1RedOne's examples, he implements his GUI inside of his script. However, I surmised that we might be able to get around this by using "Get-Content", which retrieves information from a file and sets information as the $inputXML object. As a small aside, I asked /u/1RedOne about this, and to my surprise, it was something useful. That is all to say, if you have an idea and it just might work, share it! You might solve a problem for someone else.
So, to make that happen, the first line of our code is:
$inputXML = Get-Content "$PSScriptRoot\gui.xaml"$PSScriptRoot is a dynamic directory which is created based on the location of the running script. It's the same thing as using "." if you are in the same directory (check the console pane). However, if you open the script after-the-fact, your console might not be in the same directory as the target script.
Under the "Load XAML Objects In PowerShell" section, edit the following to be:
$xaml.SelectNodes("//*[@Name]") | %{
try {Set-Variable -Name "$($_.Name)" -Value $Form.FindName($_.Name) -ErrorAction Stop}
}Basically, we're removing the portions that output text to the console. This is useful if you create executables with PS2EXE-GUI.
To manipulate the controls we've created (and named) in Powershell with Intellisense (the tab completion thingy), press F5 to run the script. Should the naming and everything match up, we are now able to call the following objects:
$bSubmit
$lLabel
$tbTextBox
$pbPassword
So, let's change a few values. Since these scripts run top to bottom (unless functions or events are called), the first properties our controls will see are from gui.xaml. We're going to change those by directly calling them from Powershell.
$bSubmit.Content = "This Button"
$lLabel.Content = "Ehhhh"
$tbUsername.Text = "UserName"If you typed these into your Scripting pane, you'll notice that as soon as you hit ".", all the possible properties are shown (some have value, some do not). Now highlight over this new code and press F8 (Run Selection). Once that is done, in the console, type in:
$bSubmit.ContentHey, that's looking good, eh? Check the other two properties in the Console pane:
$lLabel.Content
$tbUsername.TextNow we are getting down to the last portion. No good User Login page is useful without first checking if values are present and changed from defaults. To do that, we are creating an event handler for our button. (Like This) Maybe you want the button to be a right click or something else... or maybe you're just curious as to what each control can listen for... To check the list of events per control (easily), go to Visual Studio and click on a control. In the Property view, click on the Lightning Bolt in the Name row. Events in Powershell are as easy as calling the control, then adding ".Add_Event()", where Event would be the event you're listening for.
So, let's get to it! Let's have our button listen for a mouse click and run an if statement to check for updated and filled content. Source snippet. If the statements all pass the checks, we're going to update $lLabel's .Content to "You pressed the button." This will show the label who really is in charge here.
Finally, we are going to open our form. The form was created as $Form. One of the methods available in $Form is .ShowDialog(). So, let's finish the script off with this:
$Form.ShowDialog() | Out-NullSave and run your script. Make sure to click the button, change some values, and close the form. Go back to the console and check the following controls:
$tbUsername.Text
$pbPassword.Password
$lLabel.ContentI hope this all is useful to somebody! This is my first public tutorial. Be gentle and make sure to ask questions!
Some abbreviations
"|" is not an L, it's a pipe. This is used a few times to "pipe" the output of one cmdlet or object to another cmdlet.
Get-ChildItem | Where {$_.Name -eq "xaml.ps1"}
% is shorthand for a ForEach statement.
Instead of writing ForEach ($control in $inputXAML){do-soemthing}, we can just write $inputXAML | % {do-something}
We used the following for control items (and some we didn't use)
tb = TextBox
l = label
pb = PasswordBox
b = Button (not conventional, just personal preference. Visual Studio will get mad at you if you try to do this with C# or VB.Net)
tv = TreeView
lb = ListBox
cb = ComboBox
And so on...
Edit: Edits on the post thus far are grammatical and clarifying statements that I thought needed touching up.
Edit2: Well, not the second edit. I found a lot of grammatical and otherwise nonsensical errors in my write-up that have been revised. However this is to bring to your attention that I've added an Event Listeners section to the guide. Please review if you're having issues with the code!
r/PowerShell • u/fullenw1 • Jan 02 '19
Information Courses to take before Microsoft Virtual Academy is shutting them down
According to Microsoft:
To simplify your tech training journey, we are consolidating our learning resources and retiring Microsoft Virtual Academy in phases, beginning on January 31, 2019.
Complete site retirement is scheduled for later in 2019.
Check your MVA Dashboard frequently for courses you have started that are retiring.
To earn your certificates of completion, be sure to finish any courses by January 31, 2019.
There are some very excellent courses there and I didn't find any equivalent anywhere else.
What's new in PowerShell 5==> still valid and accurate because this is the most deployed versionhttps://mva.microsoft.com/en-US/training-courses/whats-new-in-powershell-v5-16434
Getting started with Microsoft PowerShellhttps://mva.microsoft.com/en-US/training-courses/getting-started-with-microsoft-powershell-8276
Advanced Tools & Scripting with PowerShell 3.0 Jump Start==> Don't be scared by the version number because the information is still valid and accurate for PowerShell 5https://mva.microsoft.com/en-US/training-courses/advanced-tools-scripting-with-powershell-30-jump-start-8277
Getting Started with PowerShell Desired State Configurationhttps://mva.microsoft.com/en-US/training-courses/getting-started-with-powershell-desired-state-configuration-dsc-8672
Advanced PowerShell Desired State Configuration (DSC) and Custom Resourceshttps://mva.microsoft.com/en-US/training-courses/advanced-powershell-desired-state-configuration-dsc-and-custom-resources-8702
Replacement of Microsoft Virtual Academy
Microsoft Learn is the new learning platform
https://docs.microsoft.com/en-us/learn/
They have also a partnership with:
LinkedIn learning (paying and owned by Microsoft)
https://www.linkedin.com/learning/mePluralSight (paying)
https://www.pluralsight.comEdx
https://www.edx.org
The certification path of Edx courses is here: https://academy.microsoft.com/en-us/professional-program/
You can take free Edx courses, but if you want a certificate you have to pay 99$ per course certificate
r/PowerShell • u/spoonstar • Apr 25 '19
Skills milestone achieved!
When I came into my first IT job five years ago, the place was a mess. GPOs were broken, random bat files everywhere, no model-independent OS deployment in place, lots of manual installers, 2500 users running as local admin, etc. Since then, I've taken it upon myself to fix every single one of those issues, and they are fixed. Business is happy, other techs are happy, great.
None of that gives me the same sense of accomplishment as today, when I got my first git repo to pass PSScriptAnalyzer rules, run Pester tests, and deploy to a centralized script location.
The rest of my department just uses my scripts - there's not much drive for understanding, but I needed an audience for my accomplishment.
Thanks for being a great resource, everyone.
r/PowerShell • u/JohnSavill • Apr 29 '21
Information Using the new Secrets Management module for secrets in scripts - What it is and demos.
r/PowerShell • u/just4PAD • May 30 '25
Misc Taking scripts from job to job?
Do y'all ask your management if you can take them, or just do it? Have you been told no due to whatever IP clause? Obviously given you have nothing dumb like hard hostnames/people names/file paths/etc. I wouldn't take scripts that do things that handle a business-specific function... but that also feels like a gray area at times.
r/PowerShell • u/Wireless_Life • Jul 12 '22
Information PowerShell Console Experience Cheat Sheet
r/PowerShell • u/DerBootsMann • Jun 22 '19
Information Download the new Windows Terminal (Preview)
r/PowerShell • u/Ta11ow • May 03 '19
News PSKoans: Learn PowerShell concepts using Pester! with Joel Sallow
r/PowerShell • u/Arkiteck • May 04 '22
News Major update to the PowerShell Extension for Visual Studio Code
r/PowerShell • u/MadBoyEvo • Jun 17 '19
Easy to use Charts and Tables using PowerShell - and more
In the beginning of this year (last days of December 2018 maybe) I was fascinated with one project called ReportHTML. At first, I wanted to use that project to create my reports with it, but the more I worked with it, the more I noticed that it's a bit outdated, and some things are harder to use than they should. It was a bit slow, and it was easy to make mistakes. In December last year, I've decided to fork it, and after six months, my project is an entirely different product, but at the same time without ReportHTML, I wouldn't have created it. I mention this because I want to make sure Matthew Quickenden gets a lot of credit for this one. Without him, I would most likely go in a different direction.
Anyways, during the last six months, PSWriteHTML (that's how it's called) has grown up and allowed me to create some nice stuff with it. I've managed to create four small projects with it - all having their approach to a problem with a single goal - You're supposed to know PowerShell only - NO HTML, NO CSS, NO JAVASCRIPT.
Today I wanted to introduce something I've worked on (on and off) in the last couple of weeks. Something that I've promised before: Charts in Dashimo, lots of icons and some more control over Tables and how things look like: Here's a full article on how to use new features (charts, tables and so on):
Dashimo - Charts/Tables and other features - https://evotec.xyz/dashimo-pswritehtml-charting-icons-and-few-other-changes
But if you've never seen or read about Dashimo/Emailimo/Statusimo or Out-HtmlView before I encourage you to take a look.
Dashimo - https://evotec.xyz/meet-dashimo-powershell-generated-dashboard/ - Pretty Tables :-)
Dashimo - https://evotec.xyz/dashimo-easy-table-conditional-formatting-and-more/ - Pretty Tables with Conditional Formatting that allows you to provide a visual representation of your data easily.
Emailimo - https://evotec.xyz/meet-emailimo-new-way-to-send-pretty-emails-with-powershell/ - this project is supposed to make it easy to send emails. I know most of you will say sending email is easy, but to me, sending pretty emails was always a horror in development. Knowing HTML / CSS how all that stuff goes together, how to make sure some stuff is bold, some stuff has colors it was driving me crazy. Well, this one is supposed to make it pretty easy. Just PowerShell knowledge. You don't have to know what DIV/P/A and other tags mean and how they go together.
Out-HtmlView - https://evotec.xyz/out-htmlview-html-alternative-to-out-gridview/ - this one is supposed to make it easy to display content right away on the screen as HTML - and when you get that on the screen you can export it to EXCEL / PDF directly from the browser. Pretty handy
Statusimo - https://evotec.xyz/meet-statusimo-powershell-generated-status-page/ - this one is supposed to deliver a way to provide your STATUS of services you have in your company. I have a plan to connect it with this module: https://evotec.xyz/powershell-way-to-get-all-information-about-office-365-service-health/ so that one can have a visual representation of Office 365 Status that doesn't require a login and can be connected/manipulated with other systems. Not yet sure how to connect it - but you should expect Statusimo to get that functionality at some point. Most likely, it will be able to take any data in the form of tables and make it into Status. But that's for another day.
As with my all projects all is open source so you can dive in, fix it, break it, take parts of it, whatever:
PSWriteHTML - https://github.com/EvotecIT/PSWriteHTML
Statusimo - https://github.com/EvotecIT/Statusimo
Dashimo - https://github.com/EvotecIT/Dashimo
Emailimo - https://github.com/EvotecIT/Emailimo
If you want to see examples of Dashimo generated HTML (it's a single static HTML file that can be simply copied over to anywhere - all as one bundle):
Example Line Charts - https://evotec.xyz/wp-content/uploads/2019/06/ExampleChartsLine.html
Example Charts Bar - https://evotec.xyz/wp-content/uploads/2019/06/ExampleChartsBar.html
Example Charts Mix with Tables - https://evotec.xyz/wp-content/uploads/2019/06/ExampleChartsMix.html
Example Tabs - https://evotec.xyz/wp-content/uploads/2019/06/ExampleTabs.html
Complicated Example with different features - https://evotec.xyz/wp-content/uploads/2019/06/DashboardMixedContent.html
For picking colors I've created a simple page: https://evotec.xyz/wp-content/uploads/2019/05/Example-Colors.html I should probably create one for picking Icons as well, but maybe a bit later.




r/PowerShell • u/joeyaiello • Jan 10 '18
PowerShell Core 6.0: Generally Available (GA) and Supported!
r/PowerShell
•
u/farag2
•
May 21 '20
Script Sharing [PowerShell Script] Setup Windows 10
I believe it would be useful for the community so...
"Windows 10 Sophia Script" is a set of functions for Windows 10 fine-tuning and automating the routine tasks 🏆
Core features
Set up Privacy & Telemetry;
Turn off diagnostics tracking scheduled tasks;
Set up UI & Personalization;
Uninstall OneDrive "correctly";
Interactive prompts;
Change %TEMP% environment variable path to %SystemDrive%\Temp
Change location of the user folders programmatically (without moving user files) within interactive menu using up/down arrows and Enter key to make a selection
"Desktop";
"Documents";
"Downloads";
"Music";
"Pictures"
"Videos.
Uninstall UWP apps from all accounts with exception apps list with pop-up form written in WPF;
Turn off Windows features;
Remove Windows capabilities with pop-up form written in WPF;
Create a Windows cleaning up task in the Task Scheduler;
A toast notification will pop up a minute before the task starts
Create tasks in the Task Scheduler to clear
%SystemRoot%\SoftwareDistribution\Download
%TEMP%
Unpin all Start menu tiles;
Pin shortcuts to Start menu using syspin.exe
Three shortcuts are preconfigured to be pinned: Control Panel, "old style" Devices and Printers, and Command Prompt
Turn on Controlled folder access and add protected folders using dialog menu;
Add exclusion folder from Microsoft Defender Antivirus scanning using dialog menu;
Add exclusion file from Microsoft Defender Antivirus scanning using dialog menu;
Refresh desktop icons, environment variables and taskbar without restarting File Explorer;
Many more File Explorer and context menu "deep" tweaks.
Download from Github
If you find bugs or bad translation, feel free to report it to me.
r/PowerShell • u/tamtt • Oct 09 '18
Information A quick start guide for powershell I made for work.
This is now a Google Doc, I haven't used them much before so updates and replies to comments may be slow to start with.
Powershell is a shell scripting language created by Microsoft that was originally meant for server administration and as a competitor to Linux's Bourne Again SHell (BASH). Since then it has become a basic front-end for the .NET framework, WMI, and COM (the bits and pieces of windows) and the community has expanded it to include many new features. These features are released in what are called Modules - groups of commands called cmdlets all centered around one purpose. For example Active Directory has a Module, to use the cmdlets that are relevant to it you must first load the Active Directory Module.
It is also worth noting that most things in powershell are case-insensitive.
When running a script powershell will execute top-to-bottom unless flow controls (if, for, while) tell it to do something different.
Syntax
COMMANDS
Powershell follows what is called a verb-noun format for all its commands. The command tells powershell broadly what you would like to do.
Get-Process
Import-Csv
Set-ItemProperty
DoThis-ToThisFrom there you have parameters. These further specify how you want the thing done. They generally start with a dash "-" and then a name.
Get-ADUser -Identity "username"In the space after a parameter you put the argument, this is user input that further specifies what to do. In the above example it's the "username"
VARIABLES
Variables are ways to hold data. In Powershell they adapt to what's inside them which means the type is automatically determined - this isn't important generally, but it is sometimes important to know. Variables are always referenced with a dollar sign and assigned with the = sign:
$variable
$variable = "this"You can change the type of variable with square brackets:
[string]$variable = "this"
[int]$variable = 123Arrays are groups of things and symbolised by an @ symbol and some brackets.
$group = @(1, 2, 3, 4, 5, 6)To select a particular part of an array you index with square brackets. You can do this from the start with a positive number (0 for the first item) or a negative number (-1 for the last item). You can select more than one by separating with commas or use two dots to select all between two values.
$group[0] #The first value$group[-1] #The last value $group[2..4] #The third to the fifth value
The hash character makes everything after it a comment and powershell ignores it.
THE PIPELINE
Some commands give an output. There are a couple of things you can do with this:
1.Send it to the console (this is the default):Get-Process
2.Send it to a variable:$processes = Get-Process
3.Send it to another command with a pipe "|" (next to Z on the keyboard):Get-Process | Where-Object -Property "ProcessName" -EQ -Value "svchost"
In example 3 I used a pipe. This takes the output from the previous command and uses it as the input for the second. Where-Object is a way of filtering an object depending on certain criteria. In this example it uses the output from Get-Process to find where the -Property called "ProcessName" equals (-eq) the -Value of "svchost".
Powershell comparisons are slightly different to other languages:Equals: -eqNot equals: -neGreater than: -gtLess than: -ltLike (allows wildcards like *): -likeIsn't like: -notlikeetc. (you can look these up online)
Using the pipeline efficiently is one of the challenges of powershell and can create some pretty powerful "One-Liners". While it's a nice challenge and sometimes a good exercise to see how much you can do in one line, your scripts for production should probably split the steps into variables to allow for easier debugging.
ifs and loops
IF STATEMENTS
Flow controls in the form of ifs and loops are incredibly useful tools and are required for most things. They are written with the condition in normal brackets and the thing you want it to do in curly brackets:
if ( This ) { Do-This }I usually lay this out with tabs and line breaks for easier reading like so, but it's not required:
if ( This ) {
Do-This
} else if ( That ) {
Do-That
} else {
Do-Other
}In the above example I added the other parts of an if statement. "Else ifs" are important if you have a few different things that could happen and you wish to check for them. "Else" is used as a final case if none of the previous ifs are met. The entire bracket that contains the condition must evaluate to $true for the statement to run. If you want a lack of something to trigger the if statement you can do it a couple of different ways:
1. if (!$this) {
2. if ($this -eq $false) {
3. if ($this -ne $true) {Notice I used $false and $true above? This is because they are the absolute True and False to compare to, rather than a generic string.
You can also have multiple conditions all evaluated in one go:
-and : this returns true if both sides are true-or : this returns true if one or both sides are true-xor : this returns true if only one of the things are true
These can be grouped together with brackets, evaluate the inner brackets before the outer. WHO SAID ALGEBRA WASN'T USEFUL!
FOR LOOPS
Powershell has a couple of different for loops. There's "foreach", and the more traditional "for". Generally you will use "foreach", but it's good to know that "for" exists. For-type loops go through code a specific number of times and then stop. Say you have a variable with 10 things in it, and you want to do something for each one of these things:
foreach ( $thing in $10Things ) {
Write-Host $thing
}Notice the same format as the if statement. The part in the brackets gives the for loop its conditions. $10Things contains 10 entries, $thing is a placeholder for the entry that we are currently working with. Write-Host just puts the result of whatever comes after into the command line. In this example it runs through each of the $10Things one by one and writes out each $thing to the console.
WHILE LOOPS
These are indefinite loops and will keep going until a condition is no longer true. Think of them like an if statement that just won't quit until it becomes $false. The syntax here is probably starting to become familiar:
while ( $thing ) {
Do-This
}This will keep looping until whatever is in $thing becomes false. It's probably worth mentioning that you can put whatever you want in these and the if's brackets and as long as it comes back to $true or $false you're golden. For example powershell's ping "Test-Connection" has a parameter "-Quiet" that returns $true or $false depending on whether there's a connection or not. This is a common condition for if and while statements. In a while loop if the condition returns true then it executes the code and loops back to the top to check again and repeat until the condition is false.
Useful cmdlets
Get-HelpProbably the command I use most often. Put the command you're struggling with after this command to get the built in instructions on how to use it.
Get-CommandThe second most used command. Know what you want to do, but don't know the command? Guess a word that's inside it and put that word after Get-Command. You might be surprised.
Import-Csv $Directory
$input = Import-Csv $DirectoryGrabs the data from a CSV and returns an object. Create a variable and make it equal to this for best usage.
$output | Export-Csv $Directory -NoTypeInformationPiping to Export-Csv is a quick way to save the information from a variable you're working on. -NoTypeInformation gets rid of an annoying powershell type it normally leaves in the top row.
Test-Path $DirectoryThis returns whether a directory exists in $true or $false format.
Get-ChildItem $Directory
gci $DirectoryLike dir back in DOS days or ls if you're a Linux head. It displays the directory underneath the directory you supply. -Recurse does all the directories below those as well. -File and -Directory say whether to only return files or folders respectively. gci is an alias (a shortened version of the command).
Where-Object
Get-Process | Where-Object -Property "ProcessName" -EQ -Value "svchost" Get-Process | Where { $_.ProcessName -eq "svchost" }A handy way of filtering an object. There are a couple of ways to do this, but the most common is to pipe an object to it. I've included a couple of different formats in the example, you can filter using a script block like the bottom one if you want to save space (I'll go over that in the Extra bits section). "Where" is an alias.
Select-Object Get-Process | Select ProcessNameIn much the same way "Where-Object" filters for rows, "Select-Object" filters the columns by name. If that particular column contains nested objects you can use -ExpandProperty to show them properly.
Sort-Object Get-Process | Sort ProcessNameThis is your basic Sort A-Z on a column. You can do other things with the parameters. Try running it through Get-Help to find out what!
Out-GridView
Get-Process | ogvOut-GridView or ogv displays the data in a separate window with some basic filtering and sorting capabilities.
Extra bits
When you use a pipe into a command you access the information in the pipe using the variable $_
Should you need to access a particular column of a variable and you would like to avoid using select-object, you can use dot notation $Processes.ProcessName This will list all the process names in the object but nothing else.
If you want to use dot notation inside double quotes you need to create a container for them:
Write-Host "The process is called $($Processes.ProcessName)"You can put an entire command in there if you want:
Write-Host "The processes running are: `n $(Get-Process)"The backtick is the powershell escape character. Put it before a character you don't want powershell to evaluate as it normally would. You can also follow it with an n, r, or t to add a new line, carraige return, or tab respectively.
Single quotes will not evaluate anything and pass an exact string whether or not it has special characters in it.
r/PowerShell • u/MadBoyEvo • Mar 16 '21
Script Sharing Advanced HTML reporting in PowerShell
Today I've spent some time and wrote a blog post about new features of PSWriteHTML. While it says in the title Advanced HTML reporting it's actually advanced in terms of what you can achieve, but not complicated to use.
Here's Search via Alphabet

Search using Search Builder

Sorting dates

Condtional formatting based on dates, numbers, strings with complicated logic

And future features - maps :-D

All this doable often with 1-5 lines of code. For example
Get-Process | Select-Object -First 5 | Out-HtmlView -SearchBuilder -Filtering {
New-TableCondition -Name 'PriorityClass' -Value 'Normal' -HighlightHeaders Name,Id -BackgroundColor Red
}There are also heavy improvements in terms of performance where you're now able to store 50k-100k records in a single HTML file and still have responsive HTML.