PowerShell 是一个可以操作对象的高级shell,是一个支持模块的shell。
如何编写模块?参考:http://www.jb51.net/article/56229.htm 基本上就是在模块目录下写一个包含有一些函数的文件,一个这种文件就是一个模块,然后配之以一个同名(不同扩展名)的manifest文件
两种注释方式:
段注释:
....
#>
1
2
3
4
5
....
#>
行注释:
#this is comment
1
#this is comment
实例:
web请求:
方法2:
PS3> $(New-Object -TypeName System.Net.WebClient).downloadstring("https://baidu.com")
1
PS3>$(New-Object-TypeNameSystem.Net.WebClient).downloadstring("https://baidu.com")
文本处理:
获取所有的IPv4地址:
PS C:\Users\phpor> ipconfig |Select-String ipv4 |ForEach-Object {$a=$_ -split ":" ; if($a) {$b=$a[1] -split "\(" ;$b[0].trim()}}
172.16.161.13
10.0.2.15
192.168.56.1
1
2
3
4
PSC:\Users\phpor>ipconfig|Select-Stringipv4|ForEach-Object{$a=$_-split":";if($a){$b=$a[1]-split"\(";$b[0].trim()}}
172.16.161.13
10.0.2.15
192.168.56.1
获取ifconfig的ipv4地址:
ifconfig|Select-String -Pattern "\s*inet\s([0-9.]+)"|foreach {$_.Matches.Groups[1].Value}
1
ifconfig|Select-String-Pattern"\s*inet\s([0-9.]+)"|foreach{$_.Matches.Groups[1].Value}
注意: 正则表达式的正确使用使得事情变得更加利索
多个对象之间用逗号分隔:
PS C:\Users\phpor> "a", "b"
a
b
1
2
3
PSC:\Users\phpor>"a","b"
a
b
单引号与双引号:
PS C:\Users\phpor> $word="World"
PS C:\Users\phpor> "Hello, $word"
Hello, World
PS C:\Users\phpor> 'Hello, $word'
Hello, $word
1
2
3
4
5
6
7
PSC:\Users\phpor>$word="World"
PSC:\Users\phpor>"Hello, $word"
Hello,World
PSC:\Users\phpor>'Hello, $word'
Hello,$word
单引号中的单引号,双引号中的双引号:
PS C:\Users\phpor> """a"""
"a"
PS C:\Users\phpor> '''a'''
'a'
1
2
3
4
5
PSC:\Users\phpor>"""a"""
"a"
PSC:\Users\phpor>'''a'''
'a'
单引号中连续的两个单引号解释为1个单引号,双引号中连续的两个双引号解释为1个双引号
转移字符
一般都是用反斜线转义,但是powershell中使用反引号来转义,如:
PS C:\Users\phpor> "a`"b"
a"b
PS C:\Users\phpor> "a`nb"
a
b
1
2
3
4
5
PSC:\Users\phpor>"a`"b"
a"b
PS C:\Users\phpor> "a`nb"
a
b
命令结果赋值给变量的写法:
PS C:\Users\phpor> $a=$(get-date)
PS C:\Users\phpor> $a
2017年2月18日 23:49:21
PS C:\Users\phpor> $a=get-date
PS C:\Users\phpor> $a
2017年2月18日 23:49:32
PS C:\Users\phpor>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
PSC:\Users\phpor>$a=$(get-date)
PSC:\Users\phpor>$a
2017年2月18日23:49:21
PSC:\Users\phpor>$a=get-date
PSC:\Users\phpor>$a
2017年2月18日23:49:32
PSC:\Users\phpor>
使用 $( cmd ) 的写法更舒服一些,更加接近于bash的写法
ISE比命令行写起来会舒服一些,不但有提示,还方便查帮助
PowerShell是已模块的形式添加功能的
选中命令时,下面就会出现命令的参数信息,按住ctrl点击命令时,参数信息界面就会隐藏