PowerShell: post-project reflections, or: PowerShell foundations
Whew!
For a recent project, I wrote around almost ~2,000 lines of PowerShell code. Not that quantity means much by itself, but it was a significant effort, and it was definitely entering the region where "normal people" with pretty good Excel skills would not have been able to do the task with the same rigour or expedience.
This was a chunk of work that solved a real business problem. Below, I list the techniques that I used. It is just applying the basics over and over again.
I've ordered the list below from fundamental to a bit more advanced. There are about 20 major dot points or concepts here.
I would consider this a pretty robust foundation that, if I had a grad under my wing, I would get them to learn and practice.
Techniques
"Coding"
Setting variables
Manually creating arrays
$numbersAsWords = @("one", "two", "three)
$numbersAsNumbers = @(1, 2, 3)
Manually creating hashtables
- Using this as an "enum" (this is more advanced)
Reading and writing data
Reading data files
Get-Content $file.json | ConvertTo-Json
Import-Csv $file.csv
Import-Csv $file.csv -Delimiter "`t"
Writing data files
Export-CSV
Export-CSV -Encoding unicode -Delimiter "`t"
- Especially relevant if there are special characters (like diacritics in European names)
Set-Content
, or>
Add-Content
, or>>
Checking stuff
Checking if something is a part of something else (
-in
for arrays,-like
for text)Checking logic, using
-eq
,-ne
,-not
,-gt
,-lt
Filtering
Filtering a table, using
Where-Object
(or?
)Array access (including after splitting a phrase into an array)
$wordParts[0]
$wordParts[1..4]
Select-Object
-First
-Last
-Property
-Unique
If
if() {} else {}
switch
Doing stuff over and over
Doing a
ForEach-Object
(or%
) loop on a table, to do:- Changing properties on each object in a table
- Adding more properties (i.e. adding moe columns) onto a table
Grouping, and looping through groups using
Group-Object
Writing functions so they can be re-used
function eatSomething ($food) {}
Text manipulation
Text manipulation
.split
or-split
-join
.Substring()
.Trim()
Using string interpolation
"I like to eat $food"
"I like it when my $food is $($food.colour)"
Advanced stuff
- Dot-sourcing
- Using advanced data types
- like
[List[]]
and[StringBuilder]
- like
- Stopwatch
- Using code from a library/module (someone else's code)