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 }
你的 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