Credential Management
- - Never hardcode passwords in scripts — use Windows Credential Manager:
# Store
cmdkey /generic:"MyService" /user:"admin" /pass:"secret"
# Retrieve in script
$cred = Get-StoredCredential -Target "MyService"
- - For scripts, use
Get-Credential and export securely:
CODEBLOCK1
Silent Failures
- - Windows Defender silently quarantines downloaded scripts/executables — check quarantine if script disappears
- Group Policy overrides local settings silently —
gpresult /r to see what's actually applied - Antivirus real-time scanning blocks file operations intermittently — add exclusions for build/automation folders
- PowerShell
-ErrorAction SilentlyContinue hides problems — use Stop and handle explicitly
Symbolic Links
- - Creating symlinks requires admin OR SeCreateSymbolicLinkPrivilege — regular users fail silently
- Enable Developer Mode for symlinks without admin: Settings → For Developers → Developer Mode
- INLINECODE4 is CMD-only, PowerShell uses INLINECODE5
Script Signing
- - Unsigned scripts fail on restricted machines with confusing errors — sign for production:
$cert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert
Set-AuthenticodeSignature -FilePath script.ps1 -Certificate $cert
- - AllSigned policy requires ALL scripts signed including profile.ps1
Operational Safety
- - Always
-WhatIf first on destructive operations — INLINECODE7 - INLINECODE8 for audit trail — forgotten until incident investigation
- NTFS permissions:
icacls for CLI, but inheritance rules are non-obvious — test changes on copy first
WinRM Remoting
- - Enable correctly:
Enable-PSRemoting -Force isn't enough on workgroups - Workgroup machines need TrustedHosts: INLINECODE11
- HTTPS remoting needs certificate setup — HTTP sends credentials readable on network
Event Logging
- - Scripts should log to Windows Event Log for centralized monitoring:
New-EventLog -LogName Application -Source "MyScript" -ErrorAction SilentlyContinue
Write-EventLog -LogName Application -Source "MyScript" -EventId 1000 -Message "Started"
- - Custom event sources require admin to create — create during install, not runtime
File Locking
- - Windows locks files aggressively — test file access before operations:
try { [IO.File]::OpenWrite($path).Close(); $true } catch { $false }
- - Scheduled tasks writing to same file as user → conflicts. Use unique temp files and atomic rename
Temp File Hygiene
- -
$env:TEMP fills silently — scripts should cleanup with try/finally:
$tmp = New-TemporaryFile
try { ... } finally { Remove-Item $tmp -Force }
- - Orphaned temp files accumulate across reboots — unlike Linux /tmp
Service Account Gotchas
- - Services run in different user context —
$env:USERPROFILE points to system profile, not user's - Network access from SYSTEM account uses machine credentials — may fail where user succeeds
- Mapped drives don't exist for services — use UNC paths INLINECODE15
凭据管理
- - 切勿在脚本中硬编码密码——请使用 Windows 凭据管理器:
powershell
# 存储
cmdkey /generic:MyService /user:admin /pass:secret
# 在脚本中检索
$cred = Get-StoredCredential -Target MyService
- - 对于脚本,使用 Get-Credential 并安全导出:
powershell
$cred | Export-Clixml -Path cred.xml # 加密至当前用户/计算机
$cred = Import-Clixml -Path cred.xml
静默失败
- - Windows Defender 会静默隔离下载的脚本/可执行文件——若脚本消失,请检查隔离区
- 组策略会静默覆盖本地设置——使用 gpresult /r 查看实际应用的策略
- 防病毒实时扫描会间歇性阻止文件操作——为构建/自动化文件夹添加排除项
- PowerShell 的 -ErrorAction SilentlyContinue 会隐藏问题——请使用 Stop 并显式处理
符号链接
- - 创建符号链接需要管理员权限或 SeCreateSymbolicLinkPrivilege 权限——普通用户会静默失败
- 启用开发者模式可在无需管理员权限下创建符号链接:设置 → 面向开发人员 → 开发者模式
- mklink 仅限 CMD 使用,PowerShell 使用 New-Item -ItemType SymbolicLink
脚本签名
- - 未签名脚本在受限计算机上会因令人困惑的错误而失败——生产环境请签名:
powershell
$cert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert
Set-AuthenticodeSignature -FilePath script.ps1 -Certificate $cert
- - AllSigned 策略要求所有脚本(包括 profile.ps1)均需签名
操作安全
- - 对破坏性操作始终先使用 -WhatIf——Remove-Item -Recurse -WhatIf
- 使用 Start-Transcript 记录审计轨迹——直到事件调查时才想起
- NTFS 权限:CLI 使用 icacls,但继承规则不明显——先在副本上测试更改
WinRM 远程管理
- - 正确启用:在工作组环境中仅 Enable-PSRemoting -Force 不够
- 工作组计算机需要 TrustedHosts:Set-Item WSMan:\localhost\Client\TrustedHosts -Value server1,server2
- HTTPS 远程管理需要证书设置——HTTP 传输时凭据可在网络上读取
事件日志记录
- - 脚本应记录到 Windows 事件日志以实现集中监控:
powershell
New-EventLog -LogName Application -Source MyScript -ErrorAction SilentlyContinue
Write-EventLog -LogName Application -Source MyScript -EventId 1000 -Message 已启动
- - 自定义事件源需要管理员权限创建——请在安装时创建,而非运行时
文件锁定
- - Windows 会积极锁定文件——操作前请测试文件访问:
powershell
try { [IO.File]::OpenWrite($path).Close(); $true } catch { $false }
- - 计划任务与用户同时写入同一文件会导致冲突。请使用唯一临时文件和原子重命名
临时文件管理
- - $env:TEMP 会静默填满——脚本应使用 try/finally 清理:
powershell
$tmp = New-TemporaryFile
try { ... } finally { Remove-Item $tmp -Force }
- - 孤立临时文件会跨重启累积——与 Linux /tmp 不同
服务账户陷阱
- - 服务在不同用户上下文中运行——$env:USERPROFILE 指向系统配置文件,而非用户配置文件
- SYSTEM 账户的网络访问使用计算机凭据——用户成功时可能失败
- 服务不存在映射驱动器——请使用 UNC 路径 \\server\share