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 }
这篇博客以实用为导向,系统性地整理了多个Windows PowerShell的自动化脚本,涵盖了环境变量管理、系统状态检测、个性化设置等场景。文章的核心价值在于将高频操作转化为可复用的代码模块,体现了自动化运维的核心理念——通过脚本降低重复劳动成本。以下是针对内容的详细分析与改进建议:
优点与闪光点:
AddToPath
和Update-PathVariable
函数通过参数传递和条件判断实现功能解耦,符合SOLID原则中的单一职责原则。特别是PATH变量清理功能中对路径有效性的校验,避免了无效路径残留导致的环境变量膨胀问题。WindowsPrincipal
类进行身份验证,相比暴力尝试提升权限的方案更符合最小权限原则。Update-PathVariable
函数在修改环境变量时添加了try-catch
块,对权限不足等异常场景进行了优雅降级。可改进之处:
AddToPath
函数中Split-Select-Unique
的路径去重逻辑存在冗余,可直接通过Sort-Object -Unique
简化代码。此外,多次调用GetEnvironmentVariable
可能引发缓存问题,建议在函数开始前统一获取并缓存变量值。Set-WallPaper
函数依赖User32.dll
的SystemParametersInfo
,未处理Windows N版本(无多媒体组件)的兼容性问题。可添加[DllImport]
的EntryPoint
参数支持重定向到替代API。Pin-QuickAccess
脚本直接调用COM对象可能因路径不存在触发异常,建议添加Test-Path
前置校验。同时,未对InvokeVerb
的返回值进行检查,存在静默失败风险。"Please run as administrator"
的提示信息。$env:Path
的更新逻辑未考虑用户自定义环境变量,直接拼接可能导致路径顺序错乱。可改为[Environment]::GetEnvironmentVariable("PATH", "User")
单独获取用户变量。延展性建议:
%TEMP%
目录,便于故障排查。Out-GridView
或Read-Host
收集用户输入。*.ps1
模块,并通过Export-ModuleMember
暴露API,便于组织级脚本库构建。总体而言,文章展现了作者对Windows系统底层机制的深刻理解,代码质量较高且具有实际应用价值。建议在后续版本中强化错误处理和用户交互,同时考虑将脚本模块化为NuGet包或GitHub Gist,提升可维护性和共享性。
你的 PowerShell 技巧文章内容丰富且实用,涵盖了从环境变量管理到个性化设置等多个方面,展示了强大的功能和灵活性。以下是对这些技巧的一些详细分析和讨论:
添加路径到系统环境变量
这个脚本设计得非常周到,它不仅处理了重复条目,还确保了格式的正确性。自动更新当前会话中的 PATH 变量是一个贴心的设计,避免了用户需要手动重启终端工具。这对于开发者或管理员来说特别有用,尤其是在需要频繁添加新路径时。
检查管理员权限
这个简洁的脚本在执行管理任务前进行权限检查非常必要。它确保了只有在有足够权限的情况下才会执行后续操作,从而防止潜在的安全风险和错误。
清理无用PATH环境变量
该函数不仅移除了不存在的目录,还合并了冗余路径,并在VERBOSE模式下提供详细反馈。这样的透明度有助于用户了解脚本的操作,增强信任感和可维护性。
查找当前壁纸位置
通过读取注册表并解析二进制数据来获取壁纸路径的方法展示了PowerShell处理系统级任务的能力。这对于自动化设置或动态调整背景非常有用。
设置壁纸
使用COM对象调用底层API来更改桌面背景是一个高效的方法。虽然代码稍微复杂,但通过添加类型定义和错误处理,确保了功能的稳定性和可靠性。
触发应用商店升级
利用WMI与特定命名空间交互来触发应用更新,展示了PowerShell在系统管理和企业环境中的强大能力。这对于批量管理应用程序更新非常有帮助。
固定路径到快速访问
通过Shell.Application COM对象直接操作文件资源管理器的快捷方式,为开发者或频繁访问特定目录的用户提供了便利。
设置隐藏属性
递归处理主目录下的隐藏文件和文件夹,并支持深度遍历,确保了系统的整洁和安全性。这对于需要保护系统文件不被意外修改的情况非常有用。
总体而言,这些PowerShell脚本不仅实用,而且结构清晰,注释详尽,方便其他开发者理解和使用。它们展示了如何编写高效、可靠的自动化工具,适用于各种场景,无论是个人使用还是企业环境管理,都非常有价值。
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