PowerShell language is a high-level proprietary programming syntax developed by Microsoft for the key purpose of enabling system administrators to automate actions and configurations.
Whether you use PowerShell daily or even occasionally, these tips will make you insanely more productive.
CTRL+SPACE
This one's usefulness is out of this world. If you're like me, you've probably used the PowerShell tab autocomplete to find the cmdlet, parameter, or variable you're looking for. Well, let me blow your mind with CTRL+SPACE. This shortcut will display all the available options AND let you choose the one you want using the arrow keys.
List all console shortcuts
If the previous one blew your mind, get ready for more! Get-PSReadLineKeyHandler will display all the keyboard shortcuts for the PowerShell console.
Set your own console shortcuts
Let's take it one step further with Set-PSReadLineKeyHandler, which allows you to set your own console shortcuts! Here's an example of how you can associate your own script to key binding:
# Associates Ctrl+Shift+F (upper case F) to insert a Where-Object block and tsets the cursor in between the two brackets
Set-PSReadLineKeyHandler -Chord Ctrl+F -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::Insert(' | Where-Object{')
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert('}')
[Microsoft.PowerShell.PSConsoleReadLine]::BackwardChar()
[Microsoft.PowerShell.PSConsoleReadLine]::BackwardChar()
}
Write Aliases, Save Cmdlets
I know I said you can use aliases to speed things up, but as I also mentioned, you should not save them in scripts. So, now the real question is: How can be lazy AND not lazy at the same time? Well, if you use Visual Studio Code, which you should, you can configure the PowerShell extension to replace all your aliases in your code when you press Alt+Shift+F. There are also extensions for PowerShell ISE, but since it is no longer in development, I won't cover that.
$?
This is my best trick when coding. Some times try/catch is too overkill. Sometimes, I just want to know if the previous action ran without error, without getting into a whole try/catch setup. $? does just that! It returns $true if the previous step ran without error and $false if it did. That's a quick and simple way to handle errors, without setting up try/catch.
Note: For executable success, you should use $LASTEXITCODE instead
Get-Process chrome -ea SilentlyContinue if ($?){
Write-Host "Chrome is running!"
}else{
Write-Host "Chrome is not running" -ForegroundColor Red
}
FOR MORE CONTENTS:CLICK HERE: 4 Windows Tips You Must KnowCLICK HERE: SIX Windows 10 Tricks You Should Check Right Now
No comments:
Post a Comment