Just a tip #5 – Select-Object with calculated properties in PowerShell

Sometimes the value from the output might not be in the readable format, the header might be not appropriate for the value or the value is not straightforward, and sometimes there is a need of calculated field altogether…


# Get the total memory in GB from the local computer using the calculated property with Select-Object
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -Property PSComputerName, `
@{Name = 'Memory in GB'; Expression = {[Math]::Round($_.TotalVisibleMemorySize/1MB)}}

# Get the services where the names are starting with App, and display IsRunning with Yes/No using the calculated property
$IsRunning = @{
Label = "IsRunning"
Expression = {
if($_.Status -eq 'Running') { "Yes" }
else { "No" }
}
}
Get-Service -Name App* | Select-Object -Property Name, DisplayName, $IsRunning

jat5

 

Just a tip #4 – Download a zip file from the internet and extract using PowerShell.

The code below will download the .zip file from the internet, then extracts the files from the zip and opens the extracted folder…


$Url = 'https://download.sysinternals.com/files/BGInfo.zip'
$ZipFile = 'C:\ZipFolder\' + $(Split-Path -Path $Url -Leaf)
$Destination= 'C:\Extracted\'

Invoke-WebRequest -Uri $Url -OutFile $ZipFile

$ExtractShell = New-Object -ComObject Shell.Application
$Files = $ExtractShell.Namespace($ZipFile).Items()
$ExtractShell.NameSpace($Destination).CopyHere($Files)
Start-Process $Destination

Just a tip #3 – $args in PowerShell

In scripting, there are many things to experience in many ways, the traditional way is always the best practice though, the formal way is always an option…

Traditional way


Function Add
{
param
(
[Parameter(Mandatory=$true)]
<span></span>[int] $Number1,
[Parameter(Mandatory=$true)]
[int] $Number2
)
[int] $Sum = 0
$Sum = $Number1 + $Number2
return, $Sum
}

Add -Number1 4 -Number2 5

Add tip 1

Formal way


<span></span>$Add = {$args[0] + $args[1]}
. $Add 4 5

Add tip 2

PowerShell Integrated Console on VSCode – Show On Startup

I preferably use Visual Studio Code for my PowerShell scripting and it has the PowerShell extension along with intellisense and syntax highlighting, PowerShell integrated console as well, however I will use Windows PowerShell to execute the commands. VSCode has an option to show the PowerShell console on startup by default, and it annoys me a bit, so I decided to disable that option…

Open VSCode, go to File -> Preferences -> Settings or click on Manage VSCode-Manage button on Side Bar then select Settings or simply use the shortcut ‘Ctrl+,’ then search for ‘PowerShell Integrated Console Show On Startup’ option in the settings and you will see the option below, just uncheck the option highlighted below to diable the console from your next start.

VSCode-ShowOnStartup