Powershell Programming

powershell基础

  • Windows PowerShell (Figure 1)
  • Windows PowerShell ISE (Figure 2)
1
2
3
4
<command -name > -< Required Parameter Name > <Required Parameter Value >
[ -< Optional Parameter Name > <Optional Parameter Value >]
[ -< Optional Switch Parameters >]
[ -< Optional Parameter Name >] <Required Parameter Value >

帮助

1
2
3
4
5
6
7
help help
help verb-noun
man verb-noun
help about
help about_for
help about_foreach
help about_if

常用函数

1
2
3
4
5
6
7
8
9
get-alias
clear-host cls, clear
format-list fl
get-childitem gci, ls, dir
get-content gc, cat, type
get-location gl, pwd
get-member gm
remove-item ri, rm, rmdir, del, erase, rd
write-output write, echo
1
2
read-host
write-host

数据类型

  • integers
  • doubles
  • strings
  • arrays
  • hash tables
  • objects
    • processes
    • services
    • event logs
    • computers
    • XML
    • anything else…

Powershell 环境

Within a shell the environment is the term to describe the current settings.
These settings are exposed in environment variables

1
2
3
(get-item $env:\username).value

$env:username

语法要点

  1. Windows不区分大小写

  2. PowerShell casts the result based on the first variable type.

1
2
3
4
5
6
7
PS M:\> [ string ] $a="4"
PS M:\> [ int] $b =7
PS M:\> $a+$b
47
PS M:\> $b+$a
11
PS M:\>
  1. arrays
1
2
3
4
5
PS M:\> $city =(" Edinburgh "," Glasgow "," Dundee "," Aberdeen ")
PS M:\> $city [3]
Aberdeen
PS M:\> ( $city ). Length
4
  1. hash tables
1
2
3
4
5
6
7
8
9
10
11
12
PS M:\> $pops =@{" Glasgow " =976970; " Edinburgh " =488610;
>> " Aberdeen " =209460; " Dundee " =157690}
>>
PS M:\> $pops
Name Value
---- -----
Edinburgh 488610
Glasgow 976970
Dundee 157690
Aberdeen 209460
PS M:\> $pops.Values | Measure-Object -average |gm
PS M:\> ($pops.Values | Measure-Object -average ).Average