# 在PowerShell中打高尔夫球的技巧

45

-几乎完全不听马尔可格的问题

3

24

``````4e6 = 4000000
``````

2个文字的幂：

``````4KB = 4096
4MB = 4194304
4GB = 4294967296

# TB and PB suffixes also exist, but less useful for golf.
``````

19

`for(\$x=1;\$x-le10;\$x++){`...`}`

`1..10|%{`...`}`

18

``````\$x-eq\$i-and\$x-ne9
``````

``````\$x -eq \$i -and \$x -ne 9
``````

``````if(\$x%2-eq0){'even'}else{'odd'}
``````

``````switch(\$x%2){0{'even'}1{'odd'}}
``````

``````if(\$x%2-eq0){'even'}elseif(\$x%2-eq1){'odd'}else{'error'}
``````

``````switch(\$x%2){0{'even'}1{'odd'}2{'error'}}
``````

``````('even','odd','error')[\$x%2]
``````

``````nal g Get-Random;g 10;g 10;g 10
``````

``````Get-Random 10;Get-Random 10;Get-Random 10
``````

`('even','odd')[\$x%2]`仅供参考。
TheIncorrigible1

15

``````\$y=(\$x=1)+1
``````

``````\$x=1;\$y=\$x+1
``````

``````(\$h='Hello World!')
``````

``````\$h='Hello World!';\$h
``````

1

SpellingD

14

``````\$FooBarMeh='a','b','c'
switch (\$FooBarMeh)
{
'a'{'FOO'}
'b'{'BAR'}
default{'MEH'}
}
``````

FOO
BAR
MEH

2

@Joey这就是`switch -File \$path`
TheIncorrigible1

12

``````[math]::pow(\$a,\$b)
``````

``````"\$a*"*\$b+1|iex
``````

HeatfanJohn

11

``````1..5 -gt 2
``````

`-match` 也是比较运算符。

1

1

11

``````?        Where-Object
%        ForEach-Object
gu       Get-Unique
sort     Sort-Object
iex      Invoke-Expression
``````

11

``````(...|measure -ma).Maximum
``````

``````(...|measure -mi).Minimum
``````

``````(...|sort)[-1]  # maximum
(...|sort)[0]   # minimum
``````

1

wizzwizz4，2016年

@ wizzwizz4：哦，最大长度通常可以创造性地使用，不一定是10。尽管对于这种特殊情况，我不记得有帮助的实例。

1

wizzwizz4 2016年

10

# 缩短属性名称

``````\$o|select Le*
\$o|%{\$_.Length}``````

``\$a|% Length``

``````\$a.Length                # 9   #(doesn't work on array)
\$a|%{\$_.Length}          # 15
\$a|% Le*                 # 8``````

``````\$a.ToUpper()             # 12
\$a|% *per                #  9``````

``````'gaga'-replace'g','r'    # 21
'gaga'|% *ce g r         # 16``````

## 对象对象属性

`?`也可以采用（部分）属性名称，并对其应用“运算符”（以开关参数的形式）。同样，`Where-Object`如果属性名称足够长且唯一，则它可以比使用标准脚本块方法短。

``````\$a|?{\$_.Length-gt5}      # 19
\$a|? Le* -GT 5           # 14

(\$a|% Le*)-gt5           # 14 - Lengths, not objs``````

1

briantist

Joey

1
@ConnorLSW啊，是的，我打算更新它，因为我意识到您可以以这种方式传递args，这大大提高了它的实用性。大用`.ToString()`
briantist

2
@briantist，这使PowerShell变成了更具竞争力的语言，确实消除了一些烦人的.Net调用。
colsw '17

9

``````(...|measure -s).Sum
``````

``````...|%{\$s+=\$_};\$s
``````

``````...-join'+'|iex
``````

9

2

4

Vasili Syrakis 2014年

2
@Vasili：您只需两行之间只有U + 000A就可以保存文件。PowerShell不会抱怨。顺便说一句，我已经在答案中写了。换行符是文件的属性，而不是文件所使用的操作系统的属性。没有人说您不能在Windows上使用Unix行尾。
2014年

@Joey如果您使用全新安装的Windows进行了一些快速编程，则会注意到\\ x0a不能很好地配合记事本
Stan Strum，

9

`Get`动词是隐含的。这可以缩短任何`Get-Frob`时间`Frob`。经常竞争者是`date``random`

``````PS Home:\> date

Freitag, 15. November 2013 07:13:45

PS Home:\> \$Env:Path += ';D:\Users\Joey\Apps\GnuWin32\bin'
PS Home:\> date
Fr Nov 15 07:14:13 W. Europe Standard Time 2013
``````

Iszi 2013年

2

1

Iszi 2013年

Iszi 2013年

1

Iszi 2013年

8

`for` 循环的标头中可以包含0到三个语句之间的任何值：

``````for(){}
``````

``````for(\$n=0){}
``````

``````for(\$n=0;\$n-lt7){}
``````

``````while(...){}
``````

``````for(;...){}
``````

8

``````\$a="apple","orange"
\$a[0] # apple
\$a[1] # orange
``````

``````\$a,\$o="apple","orange"
\$a # apple
\$o # orange
``````

``````\$a,\$b=1..10
\$a # 1
\$b # 2..10
``````

2014年

8

``````[string]\$x
``````

``````"\$x"
``````

``````\$a = @('a','b','c')
\$a -join ' '
``````

``````\$a = @('a','b','c')
"\$a"
``````

``````[int]\$x     [float]\$x
``````

``````+\$x
``````

``````'1'+2    -> '12'
1+'2'    -> 3
``````

6

``````Get-Random -InputObject (0..10)
``````

...可以修整为...

``````Get-Random -I (0..10)
``````

...因为在这种情况下，“ I”足以`InputObject`从该命令的其他有效参数中唯一标识。

``````Get-Random (0..10)
``````

...因为`InputObject`是位置参数。

``````0..10|Get-Random
``````

``````Get-Random 11
``````

``````Random 11
``````

**注意：省略`Get-`命令名称可能会使运行时间膨胀约50,000％。如果只需要一次该命令，但要在长循环中小心使用，就可以了。*

6

``````\$z=if(\$x-eq\$y){"truth"}else{"false"}
``````

``````\$z=("false","true")[\$x-eq\$y]
``````

Joey

6

``````...-join'0'
``````

``````...-join0
``````

`-replace`也不需要您要删除匹配项的第二个参数，也可以使用
Joey

5

``````\$n=-123
``````

``````[math]::abs(\$n)
``````

``````\$n-replace'-'
``````

Joey

5

``````try{ <# something that throws errors #> }catch{}
``````

``````.{ <# something that throws errors #> }2>\$x
``````

5

``````\$a=1,2,3,4
\$a-join',';\$a-join','
\$ofs=',';"\$a";"\$a"
``````

1

5

``````PS C:\Users\matt> !1
False

PS C:\Users\matt> !0
True
``````

• 整数0为false，非零整数的值为true。
• 非零长度的字符串为true，为空或为null（本身为null）的字符串为false。

``````PS C:\Users\matt> [bool]@(0)
False
``````

1

@TimmyD非常正确。使用`int`s会更短一些
Matt

@TimmyD我想回答fizzbuzz，直到我看到你....不能击败....至少目前还没有

4

`Invoke-Expression`并且`Get-Random`还可以获得管道输入而不是参数。

``````iex 1..5-join'+'   # won't work
iex(1..5-join'+')  # does work, but has extra parentheses
1..5-join'+'|iex   # doesn't need the parentheses
``````

`random`这种情况下，可以对常见情况进行一些优化：

``````random -mi 10 31   # gets a random integer between 10 and 30
10..30|random      # much better :-)
(random 21)+10     # if needed in another expression that doesn't require extra
# parentheses
``````

4

``````function Hi{echo 'Hello, World!'};Hi
``````

``````\$Hi={echo 'Hello, World!'};&\$Hi
``````

2

`\$args`可以避免使用`params`；即`\$x={\$args[0]+2}`（甚至`\$x={2+"\$args"}`）；在某些情况下可能会保存一个字符或2个字符。您还可以将其与另一个用于多个参数的技巧结合起来：`\$x={\$a,\$b=\$args;\$a+\$b+3}`
JohnLBevan'1

4

``````\$s|% t*y
``````

``````[char[]]\$s
``````

``````\$s.ToCharArray()
``````

`\$args`特别适用于：`\$args|% t*y`

1

mazzy

MAZZY

3

### 在循环中使用布尔逻辑代替if计数器

``````1..10|%{if(\$_%2-eq0){\$o+=\$_}};\$o
``````

``````1..10|%{if(!(\$_%2)){\$o+=\$_}};\$o
``````

``````1..10|%{\$o+=\$_*!(\$_%2)};\$o
``````

2

3

``````PS C:\> [int]1.5
2

PS C:\> [int]2.5
2
``````

``````[Math]::Truncate(1.5)
[Math]::Floor(1.5)
1.5-replace'\..*'

[Math]::Truncate(\$a)
[Math]::Floor(\$a)
\$a-replace'\..*'
\$a.split('.')[0]        # literal character split, not regex pattern split
``````

3

### 反转数组

``````\$a=1,2,3,4,5
``````

``````[array]::reverse(\$a)
``````

``````\$a[(\$a.count-1)..0]
``````

``````\$a|%{\$a[-++\$i]}
``````

Joey

3

``````'a'..'z'
``````

``````0..25|%{[char](\$_+97)}
``````

`[char[]](65..90)`也是生成字母的便捷方法