Skip to content

Basic PowerShell tricks and notes Part 2

Violet edited this page Jul 2, 2023 · 16 revisions

Basic PowerShell tricks and notes Part 2

This page is part 2 of the Basic PowerShell tricks and notes series. You can find the part 1 here.

Designed for beginners and newcomers to PowerShell who want to quickly learn the essential basics, the most frequently used syntaxes, elements and tricks. It should help you jump start your journey as a PowerShell user.

The main source for learning PowerShell is Microsoft Learn websites. There are extensive and complete guides about each command/cmdlet with examples.

PowerShell core at Microsoft Learn

Also Use Bing Chat for your PowerShell questions. The AI is fantastic at creating code and explaining everything.


View all Predictive IntelliSense suggestions based on past history

Press F2 to see the complete list of the Predictive IntelliSense suggestions as you type on the PowerShell console.

More info


Where is the PowerShell command history stored?

In this directory

$env:USERPROFILE\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine

There is a file called ConsoleHost_history.txt and it contains the history of all the commands you've ever typed in PowerShell on your device. If you want to clear it, open the file, delete all of its content. If PowerShell is already open, close and reopen it to see the change.


How to clear the automatic error variable in PowerShell

$error.clear()

How to get the last error type in PowerShell

$Error[0].Exception.GetType().FullName

How to display all environment variables and their values in PowerShell

gci env:
  • The env: drive is a PowerShell provider that exposes the environment variables as a hierarchical file system.

  • The gci command is an alias for the Get-ChildItem cmdlet.


List all MSCs and CPLs for Microsoft Management Console and Control Panels in PowerShell

Get-ChildItem -Path C:\Windows\system32\* -Include *.msc, *.cpl | Sort-Object -Property Extension | Select-Object -Property Name | Format-Wide -Column 2

How to mount the EFI system partition?

mountvol u: /s

This isn't a native PowerShell cmdlet, it uses mountvol CLI.

With that command you can mount the EFI partition and assign the letter U to it, it will appear in This PC. You can browse it in PowerShell as admin.


How to check if a file is in use in PowerShell?

Here is an example function that tries to rename files given to it with the same names and if it was successful, it will consider that file not in use.

function IsFileAccessible {
    param ([System.String]$FullFileName)    
    [System.Boolean]$IsAccessible = $false
    try {
        Rename-Item $FullFileName $FullFileName -ErrorVariable LockError -ErrorAction Stop
        $IsAccessible = $true
    }
    catch {
        $IsAccessible = $false
    }
    return $IsAccessible, $FullFileName
}

You can use it like this:

(Get-ChildItem -Path 'C:\Program Files\Windows Defender' -Filter '*.exe*').FullName | ForEach-Object { IsFileAccessible -FullFileName $_ }

Choosing between PowerShell and PowerShell Preview

Use PowerShell Preview if you want to test new features and don't need to call PowerShell with its alias, pwsh, from CMD. If you do need to call it like that, use PowerShell stable.

Use cases for it are when you need to use pwsh.exe in Windows Task Scheduler.

PowerShell Preview by default doesn't set its pwsh.exe available system wide, the path to that file isn't added to the system environment variables, only PowerShell stable does that, but of course if you want to use PowerShell preview you can manually modify the PATH environment variable to have pwsh.exe of PowerShell Preview be available system wide.


Variable types in PowerShell

PowerShell variables can have types and type accelerator. The following command lists all of the types and their equivalent type accelerators. The fully qualified type names replace implicit with explicit.

[PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get

Success codes and error codes

In PowerShell, or for programming languages in general, 0 = success, 1 or anything else means failure/error.


How to get the names and AppIDs of installed apps of the current user in PowerShell?

Get-StartApps

More info


Difference between Async and Sync

Async is faster than Sync

  • Sync = waits for the previous task to finish before starting a new one

  • Async = starts multiple tasks simultaneously

PowerShell supports sync/async commands workflows, also known as parallel.


How to enable a disabled event log using PowerShell

First we create a new EventLogConfiguration object and pass it the name of the log we want to configure, then we set it to enabled and save the changes.

$logName = 'Microsoft-Windows-DNS-Client/Operational'  

$log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $logName 
$log.IsEnabled=$true 
$log.SaveChanges() 

We can confirm the change by running this command:

Get-WinEvent -ListLog Microsoft-Windows-DNS-Client/Operational | Format-List *

Using the same method we can configure many other options of the log file, just take a look at the EventLogConfiguration Class for a list of configurable properties.


Find the current user's username in PowerShell

[Environment]::UserName 
$env:username
whoami 
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name 

Most secure way


How to access properties of an object in PowerShell

For example, you can first assign the entire object to a variable:

$Preferences = Get-MpPreference 

Then call properties of that variable

$Preferences.PUAProtection 

Another method is this:

$(Get-MpPreference).puaprotection








C#


Clone this wiki locally