-
-
Notifications
You must be signed in to change notification settings - Fork 321
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 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 explaning everything.
Press F2 to see the complete list of the Predictive IntelliSense suggestions as you type on the PowerShell console.
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.
$error.clear()$Error[0].Exception.GetType().FullNamegci env:-
The
env:drive is a PowerShell provider that exposes the environment variables as a hierarchical file system. -
The
gcicommand is an alias for theGet-ChildItemcmdlet.
Get-ChildItem -Path C:\Windows\system32\* -Include *.msc, *.cpl | Sort-Object -Property Extension | Select-Object -Property Name | Format-Wide -Column 2mountvol u: /sThis isn't a native PowerShell cmdlet, it uses mounvol 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.
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 $_ }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.
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')::GetIn PowerShell, or for programming languages in general, 0 = success, 1 or anything else means failure/error.
Get-StartAppsAsync 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.
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.
[Environment]::UserName $env:username whoami [System.Security.Principal.WindowsIdentity]::GetCurrent().Name Most secure way
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- Create AppControl Policy
- Create Supplemental Policy
- System Information
- Configure Policy Rule Options
- Policy Editor
- Simulation
- Allow New Apps
- Build New Certificate
- Create Policy From Event Logs
- Create Policy From MDE Advanced Hunting
- Create Deny Policy
- Merge App Control Policies
- Deploy App Control Policy
- Get Code Integrity Hashes
- Get Secure Policy Settings
- Update
- Sidebar
- Validate Policies
- View File Certificates
- Microsoft Graph
- Firewall Sentinel
- Data Analysis in AppControl Manager
- Compare Policies
- Protect
- Microsoft Security Baselines
- Microsoft Security Baselines Overrides
- Microsoft 365 Apps Security Baseline
- Microsoft Defender
- Attack Surface Reduction
- Bitlocker
- Device Guard
- TLS Security
- Lock Screen
- User Account Control
- Windows Firewall
- Optional Windows Features
- Windows Networking
- Miscellaneous Configurations
- Windows Update
- Edge Browser
- Certificate Checking
- Country IP Blocking
- Non Admin Measures
- Group Policy Editor
- Manage Installed Apps
- File Reputation
- Audit Policies
- Cryptographic Bill of Materials
- Intune
- Configuration Service Provider (CSP)
- Service Manager
- Exploit Mitigations
- Sandbox Maker
- WinGet Management
- Duplicate Photos Finder
- EXIF Manager
- Download Manager
- Bootable Drive Maker
- Introduction
- How To Generate Audit Logs via App Control Policies
- How To Create an App Control Supplemental Policy
- The Strength of Signed App Control Policies
- How To Upload App Control Policies To Intune Using AppControl Manager
- How To Create and Maintain Strict Kernel‐Mode App Control Policy
- How to Create an App Control Deny Policy
- App Control Notes
- How to use Windows Server to Create App Control Code Signing Certificate
- Fast and Automatic Microsoft Recommended Driver Block Rules updates
- App Control policy for BYOVD Kernel mode only protection
- EKUs in App Control for Business Policies
- App Control Rule Levels Comparison and Guide
- Script Enforcement and PowerShell Constrained Language Mode in App Control Policies
- How to Use Microsoft Defender for Endpoint Advanced Hunting With App Control
- App Control Frequently Asked Questions (FAQs)
- System Integrity Policy Transformations | XML to CIP and Back
- About Code Integrity Policy Signing
- How To Install Microsoft Store Apps Completely Offline
- Create Bootable USB flash drive with no 3rd party tools
- Event Viewer
- Group Policy
- How to compact your OS and free up extra space
- Hyper V
- Git GitHub Desktop and Mandatory ASLR
- Signed and Verified commits with GitHub desktop
- About TLS, DNS, Encryption and OPSEC concepts
- Things to do when clean installing Windows
- Comparison of security benchmarks
- BitLocker, TPM and Pluton | What Are They and How Do They Work
- How to Detect Changes in User and Local Machine Certificate Stores in Real Time Using PowerShell
- Cloning Personal and Enterprise Repositories Using GitHub Desktop
- Only a Small Portion of The Windows OS Security Apparatus
- Rethinking Trust: Advanced Security Measures for High‐Stakes Systems
- Clean Source principle, Azure and Privileged Access Workstations
- How to Securely Connect to Azure VMs and Use RDP
- Basic PowerShell tricks and notes
- Basic PowerShell tricks and notes Part 2
- Basic PowerShell tricks and notes Part 3
- Basic PowerShell tricks and notes Part 4
- Basic PowerShell tricks and notes Part 5
- How To Access All Stream Outputs From Thread Jobs In PowerShell In Real Time
- PowerShell Best Practices To Follow When Coding
- How To Asynchronously Access All Stream Outputs From Background Jobs In PowerShell
- Powershell Dynamic Parameters and How to Add Them to the Get‐Help Syntax
- RunSpaces In PowerShell
- How To Use Reflection And Prevent Using Internal & Private C# Methods in PowerShell