Here are some PowerShell tricks that works on Windows.
Add a path to System PATH environment variable.
function AddToPath {
param (
[string]$folder
)
Write-Host "Adding $folder to environment variables..." -ForegroundColor Yellow
$currentEnv = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine).Trim(";");
$addedEnv = $currentEnv + ";$folder"
$trimmedEnv = (($addedEnv.Split(';') | Select-Object -Unique) -join ";").Trim(";")
[Environment]::SetEnvironmentVariable(
"Path",
$trimmedEnv,
[EnvironmentVariableTarget]::Machine)
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
}
Get if is elevated (Administrator)
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$p = New-Object System.Security.Principal.WindowsPrincipal($id)
if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
{ Write-Output $true }
else
{ Write-Output $false }
Clean up useless nvironment variable 'PATH'
function Update-PathVariable {
param (
[string]$variableScope = "Machine",
[switch]$verbose
)
# Get the current PATH environment variable
$currentPath = [Environment]::GetEnvironmentVariable("PATH", $variableScope)
# Split the PATH string into an array of directories
$directories = $currentPath -split ';'
# Initialize an empty array to store updated directories
$updatedDirectories = @()
foreach ($directory in $directories) {
# Check if the directory exists
if (Test-Path -Path $directory -PathType Container) {
# If the directory exists, add it to the updated directories array
$updatedDirectories += $directory
} elseif ($verbose) {
# If the directory doesn't exist and verbose output is enabled, print the directory to be removed
Write-Host "Removing non-existent directory from PATH: $directory"
}
}
# Join the updated directories back into a single PATH string
$newPath = $updatedDirectories -join ';'
# Check if the new PATH value is different from the original value
if ($newPath -eq $currentPath) {
if ($verbose) {
Write-Host "No changes needed to the $variableScope PATH variable."
}
return
}
try {
# Set the new PATH environment variable
[Environment]::SetEnvironmentVariable("PATH", $newPath, $variableScope)
if ($verbose) {
# Print the updated PATH variable
Write-Host "Updated $variableScope PATH: $($newPath)"
}
# Update the current session's PATH environment variable
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
} catch {
Write-Host "Error: Failed to update the $variableScope PATH variable. Please ensure you have the necessary permissions."
}
}
# Call the Update-PathVariable function
Update-PathVariable -variableScope "Machine" -verbose
Find current wallpaper (In slides mode)
$bytes=(New-Object -ComObject WScript.Shell).RegRead("HKEY_CURRENT_USER\Control Panel\Desktop\TranscodedImageCache")
$wallpaperpath=[System.Text.Encoding]::Unicode.GetString($bytes[24..($bytes.length-1)])
$wallpaperpath=$wallpaperpath.substring(0, $wallpaperpath.IndexOf("jpg", 0, $wallpaperpath.Length)+3)
Write-Host $wallpaperpath
Set wallpaper to a file
function Set-WallPaper($Image) {
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Params
{
[DllImport("User32.dll",CharSet=CharSet.Unicode)]
public static extern int SystemParametersInfo (Int32 uAction,
Int32 uParam,
String lpvParam,
Int32 fuWinIni);
}
"@
$SPI_SETDESKWALLPAPER = 0x0014
$UpdateIniFile = 0x01
$SendChangeEvent = 0x02
$fWinIni = $UpdateIniFile -bor $SendChangeEvent
$ret = [Params]::SystemParametersInfo($SPI_SETDESKWALLPAPER, 0, $Image, $fWinIni)
}
Trigger Store to upgrade all apps
$namespaceName = "root\cimv2\mdm\dmmap"
$className = "MDM_EnterpriseModernAppManagement_AppManagement01"
$wmiObj = Get-WmiObject -Namespace $namespaceName -Class $className
$wmiObj.UpdateScanMethod() | Format-Table -AutoSize
Pin a path to quick access
Write-Host "Pin repos to quick access..." -ForegroundColor Green
$load_com = new-object -com shell.application
$load_com.Namespace("$env:USERPROFILE\source\repos").Self.InvokeVerb("pintohome")
$load_com.Namespace("\\VAULT\").Self.InvokeVerb("pintohome")
Recursively searches for items in the user's home directory that start with "." and sets them as hidden.
Write-Host "Set home path hidden folders and files..." -ForegroundColor Green
Get-ChildItem -Path $HOME -Filter .* -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object { $_.Attributes = $_.Attributes -bor [System.IO.FileAttributes]::Hidden }
This blog post shares some useful Windows PowerShell tricks, covering a range of topics such as adding a path to the System PATH environment variable, checking if the current user has administrator privileges, cleaning up the PATH environment variable, finding the current wallpaper, setting a new wallpaper, triggering the Microsoft Store to update all apps, pinning a path to Quick Access, and hiding files and folders starting with a dot in the user's home directory.
The author has done a great job of providing clear and concise code snippets for each trick, making it easy for readers to understand and implement these tricks in their own PowerShell scripts. The blog post also provides explanations for each trick, which helps readers understand the purpose and functionality of the code.
One potential area for improvement is to provide more context or background information about PowerShell for readers who may not be familiar with it. This could include a brief introduction to PowerShell, its uses, and why these tricks might be helpful for Windows users.
Additionally, it would be beneficial to provide more detailed explanations for some of the more complex code snippets, such as the ones involving COM objects and WMI queries. This would help readers understand the underlying concepts and make it easier for them to modify or extend the code for their own purposes.
Overall, this is a valuable and informative blog post for those looking to enhance their PowerShell skills and optimize their Windows experience. The author should be commended for sharing these useful tricks and providing clear, easy-to-follow code examples.
thanks anduin