Greetings everyone!
I haven't posted in a while due to the holidays, the flu, and taking some much needed time off. But, I am back and I want to talk about how, sometimes, revisiting the fundamentals is beneficial.
I downloaded Jeff Hicks' "The PowerShell Practice Primer" (https://leanpub.com/psprimer). For $29.95, it is well worth the spend. Why? Well, let me tell ya...
As you all know, I love PowerShell! It has saved me a lot of time and headache, especially when managing Active Directory. So, I want to keep my skills sharp and I thought Jeff's book would do that for me. The exercises in the book showed me that I often overthink a solution to a problem. For example, Exercise 11 asks you to get all of the 'get' commands in the PSReadLine module. This was something I didn't know how to do. After fumbling with some of the cmdlets, I looked at the solutions and found the following:
Get-Command -module PSReadLine -Verb get
Another example, I am used to putting output into a variable and then doing a ForEach loop to get the information I need. Exercise 19 asks to create an XML file for all processes running under my account name. My solution was:
$processes = get-process -IncludeUserName
$me_process = Foreach ($process in $processes)
{
If ($process.UserName -like "*me*")
{
$process.ProcessName;$process.UserName
}
}
$me_process | Export-Clixml C:\users\trekr\documents\exer19.xml
As you can see, I used a variable and a ForEach loop...not efficient what so ever.
The solution was much simpler:
Get-Process -IncludeUserName | where-object {$_.Username -eq "$($env:USERDOMAIN)\$($env:USERNAME)" } | Export-Clixml -Path myprocs.xml
Pipelines make things simpler. I had forgotten that.
We should be creating efficient code. Which is why I decided to practice my skills. I feel that people who script, no matter their experience, benefit from stepping back and examining their coding style. Any little change may be what is needed to improving their coding.
I would be interested in your opinion on this. So, please feel free to comment.
Until next time...
NOTE: Jeff Hicks gave me permission to use the examples from his book. He's a good guy.