๐ค
PowerShell
้ฟๅ ๅธธ่ง็ PowerShell ้่ฏฏโโ่พๅบ่กไธบใๆฐ็ป้ท้ฑๅๆฏ่พ่ฟ็ฎ็ฌฆ้ท้ฑใ
ๅฎๅ
จ้่ฟ
ๆ่ฝ่ฏดๆ
name: PowerShell description: Avoid common PowerShell mistakes โ output behavior, array traps, and comparison operator gotchas. metadata: {"clawdbot":{"emoji":"๐ต","requires":{"bins":["pwsh"]},"os":["linux","darwin","win32"]}}
Output Behavior
- Everything not captured goes to output โ even without
returnorWrite-Output returndoesn't stop output โ previous uncaptured expressions still outputWrite-Hostbypasses pipeline โ use for display only, not data- Assign to
$nullto suppress โ$null = SomeFunction [void]cast also suppresses โ[void](SomeFunction)
Array Gotchas
- Single item result is scalar, not array โ
@(Get-Item .)forces array - Empty result is
$null, not empty array โ check withif ($result)carefully - Array unrolling in pipeline โ
@(1,2,3) | ForEachsends items one by one +=on array creates new array โ slow in loops, use[System.Collections.ArrayList],is array operator โ,$itemwraps single item in array
Comparison Operators
-eq,-ne,-gt,-ltโ not==,!=,>,<-likewith wildcards,-matchwith regex โ both return bool-containsfor array membership โ$arr -contains $item, not$item -in $arr(though-inworks too)- Case-insensitive by default โ
-ceq,-cmatchfor case-sensitive $nullon left side โ$null -eq $varprevents array comparison issues
String Handling
- Double quotes interpolate โ
"Hello $name"expands variable - Single quotes literal โ
'$name'stays as literal text - Subexpression for complex โ
"Count: $($arr.Count)"for properties/methods - Here-strings for multiline โ
@" ... "@or@' ... '@ - Backtick escapes โ
`nfor newline,`tfor tab
Pipeline
$_or$PSItemis current object โ same thing,$_more commonForEach-Objectfor pipeline โforeachstatement doesn't take pipeline-PipelineVariablesaves intermediate โGet-Service -PV svc | Where ...- Pipeline processes one at a time โ unless function doesn't support streaming
Error Handling
$ErrorActionPreferencesets default โStop,Continue,SilentlyContinue-ErrorAction Stopper command โ makes non-terminating errors terminatingtry/catchonly catches terminating โ setErrorAction Stopfirst$?is last command success โ$LASTEXITCODEfor native commands
Common Mistakes
- No space before
{inifโif($x){works butif ($x) {preferred =is assignment in conditions โ use-eqfor comparison- Function return array unrolls โ
return ,@($arr)to keep array Get-Contentreturns lines array โ-Rawfor single stringSelect-Objectcreates new object โ properties are copies, not references
Cross-Platform
pwshis PowerShell 7+ โpowershellis Windows PowerShell 5.1- Paths use
/or\โJoin-Pathfor portable - Environment vars:
$env:VARโ works on all platforms - Aliases differ across platforms โ
ls,catmay not exist, use full cmdlet names
ๅฆไฝไฝฟ็จใPowerShellใ๏ผ
- ๆๅผๅฐ้พ่พAI๏ผWeb ๆ iOS App๏ผ
- ็นๅปไธๆนใ็ซๅณไฝฟ็จใๆ้ฎ๏ผๆๅจๅฏน่ฏๆกไธญ่พๅ ฅไปปๅกๆ่ฟฐ
- ๅฐ้พ่พAI ไผ่ชๅจๅน้ ๅนถ่ฐ็จใPowerShellใๆ่ฝๅฎๆไปปๅก
- ็ปๆๅณๆถๅ็ฐ๏ผๆฏๆ็ปง็ปญๅฏน่ฏไผๅ