首页 » Mircrosoft » Powershell » Powershell基础教程:变量、循环、基本命令

Powershell基础教程:变量、循环、基本命令

作者: lesca 分类: Powershell, Tutorials, Windows 发布时间: 2012-10-24 15:05 ė浏览 9,319 次 6Comments Off on Powershell基础教程:变量、循环、基本命令

本文介绍Powershell的基础知识。

一、准备工作

检查当前执行策略

Get-ExecutionPolicy [-list]

修改执行策略

Set-ExecutionPolicy {Unrestricted | RemoteSigned | AllSigned | Restricted }
  • Restricted – 不可运行Powershell脚本,只能使用命令行交互模式。
  • AllSigned – 只有经过可信发布者签名的脚本才可运行。
  • RemoteSigned – 远程脚本需要可信发布者签名才可运行,本地脚本可直接运行。
  • Unrestricted – 所有脚本均可运行。

注释符号

Powershell中的注释符号为(#)。

# 注释

转义字符

Powershell中的转义字符为上前引号(`),位于键盘左上角的按键。

`n	# 换行

二、变量

获取成员函数或变量

$var | Get-Member
Get-ChildItem | Get-Member

获取变量类型

$var.GetType()

数组

数字下标的数组:

os=@(" linux ", " windows ")os +=@("mac")
Write-Host os [1]		# print windows
Write-Hostos			# print array values
Write-Host $os.Count	# length of array

键值对数组:

user =@{
	"frodeh" = "Frode Haug";
	"ivarm" = "Ivar Moe"
}user += @{"lailas" = "Laila Skiaker"}
Write-Host user ["ivarm"]	# print Ivar Moe
Write-Host @user			# print array values
Write-Host @user.Keys		# print array keys
Write-Hostuser.Count		# print length of array

新建对象

myhost = New-Object PSObject - Property @{
	os="";
	sw=@();
	user =@{}
}myhost.os= "linux"
myhost.sw +=@("gcc", "flex", "vim")myhost.user +=@{
	"frodeh" = "Frode Haug";
	"monicas" = "Monica Strand"
}
Write-Host myhost.os
Write-Hostmyhost.sw[2]
Write-Host $myhost.user["monicas"]

三、输入(input)

命令行参数

Write-Host "first arg is" $args[0]

从命令行输入

something = Read-Host "Say something here"
Write-Host "you said "something

通过管道输入

Write-Output "hey hey !" | .\input-pipe.ps1

通过Get-Content命令打开文件

$file = Get-Content hello.txt
Write-Host @file -Separator "`n"

通过命令获取环境信息

name = (Get-WmiObject Win32_OperatingSystem).Namekernel = (Get-WmiObject Win32_OperatingSystem).Version

四、条件与循环

条件判断操作符

Operator Meaning
-lt Less than
-gt Greater than
-le Less than or equal to
-ge Greater than or equal to
-eq Equal to
-ne Not equal to
-not Not
! Not
-and And
-or Or

if-elseif-else

if ( a -gt b ) {
	...;
} elseif ( b -gt c ) {
	...;
} else {
	...;
}

switch

short = @{ yes ="y"; nope ="n";}ans = Read-Host
switch ( ans ) {
    yes { Write-Host "yes"; break}
    nope { Write-Host "nope "; break }
    default { Write-Host "ans `??? "}
}

Where-Object/Where/?

Get-ChildItem | ? {$_.Length -gt 1KB}

Foreach-Object/Foreach/%

files = Get-ChildItem "D:\"
foreach (file in files ) {
    Write-Hostfile.Name
}

或者

Get-ChildItem "D:\" | % {
    $_.Name
}
input | % {foo += @(_)
}
Write-Host "size of foo is "foo.Count

for

for (i = 1;i -le 3; i++) {
    Write-Host "i"
}

while

while (i -le 3) {
    Write-Hosti
    $i ++
}

References:

[1] Powershell Tutorials – Erik Hjelmas

Copyright

本文出自 Lesca 技术宅,转载时请注明出处及相应链接。

本文永久链接: https://lesca.me/archives/powershell-tutorial-basics.html

Ɣ回顶部