PowerShell 随笔

$a = 1..100

脚本双击直接运行:
ftype Microsoft.PowerShellScript.1="C:WINDOWSsystem32windowspowershellv1.0powershell.exe" -command "& {%1}"
assoc .ps1=Microsoft.PowerShellScript.1


更改脚本执行策略:
set-executionpolicy remotesigned
Write-Host "Success" 输出,可以通过vbs调用powerShell脚本隐藏窗口

在命令提示符下运行ps命令方法:
powershell.exe get-childitem

运行变量中存储的命令:
$command = "Get-Process"
invoke-expression $command

单步调试,一行一行执行命令
set-psDebug -step set-psDebug -off

系统变量:$env:temp $env:OS
Get-ChildItem $env:temp

延时100秒
Start-Sleep -Seconds 100

连接字符串
$c = $a + " and " + $b

输出计算过程
$a=2;$b=3
write-host $a + $b = ($a+$b)

数组转换为字符串
$a=1,2,3
$b=[string]$a
结果显示:1,2,3

$a=1,2,3
[String]::Join("GB+",$a)+"GB"
结果显示:1GB+2GB+3G

$j=${d: es.txt} #等价于get-content

"notepad.exe" -like "notepad.???" ##一个?代表一个字符,单字符匹配

返回数组每个值类型
$m|%{$_.gettype()}

$array[-1] #最后一个元素
$array[-2] #倒数第二个元素
$array[1][2] #对二维数组进行索引
$array[20..2]
$array[-2..-20]

1,2,3,4|%{$_}
gwmi win32_computersystem|%{$_.name} #无标题
$t = gwmi win32_computersystem|format-table name -HideTableHeaders |Out-String
$t.trim() #输出无空行,去除空格 trimstart(),trimend()


在使用$a的时候,可以先强制转换类型[array]$a
$a.count的时候,需要先判断 $a.gettype().isarray 是否为True&False,如果为False,则$a.count为$null

统计字符、单词和行数:
Get-content c: est.txt |measure-object -character -word -line

创建数组,注意get-process
$myarray=@(5;"This";get-process)
$myarray[2]
$myarray.length 是87,不是3


创建临时文件:
$tempFile = [io.path]::getTempFIleName()


打开wmi:wbemtest

查找相关命令:
get-command -name *process
get-command -name get*
Get-Command -Name Clear-Host

查看wmi对象
get-wmiObject -list -namespace “rootCIMV2″ 
get-wmiobject -list "*adapter*"
gwmi
gwmi win32_networkadapter |get-member
gwmi Win32_NetworkAdapterConfiguration |where {$_.description -like "broad*"}
$j = gwmi Win32_NetworkAdapterConfiguration |where {$_.description -like "broad*"} |select ip
$j.address 此处还有问题

(Get-WmiObject Win32_operatingsystem).win32shutdown(0) #0注销,1关机,2重启
Restart-Computer -computername Server01,Server02
Stop-Computer 192.168.1.102 -force -Credential administrator

get-help get-process -examples,-full,-detailed
get-process |out-host -paging

help get-process; man get-process 分页显示帮助
help get-process -examples

获取对象的方法、属性、类型
get-service | get-member

获取该对象的属性
get-service | get-member -membertype *property

查看wsearch服务的显示名称、停止服务、查看服务状态
get-service -name wsearch
get-service | where-object {$_.Status -eq "Running"}
(get-service wsearch).displayname
(get-service schedule).stop()
(get-service wsearch).status

创建别名:
set-alias gh get-help 为get-help创建别名gh
set-alias np c:windows otepad.exe 为命令创建别名np
remove-item alias:gh 删除别名

输出格式:
get-service | format-list
(get-service wsearch)| format-list

get-service | format-table name, Servicetype, Canshutdown | out-file -filepath c:a.txt
get-process | out-file -filepath c:a.txt -append 追加

get-process -name xdict | format-table processname,id,cpu
get-process -name xdict | format-table processname,id,cpu -hidetableheaders #省略标题名称
$a |get-member |format-table -wrap #被截断的列分行显示

get-childitem |format-wide -property mode -column 1 $显示指定的某一列,-column指定以几列显示

直接导出到excel,可以分单元格显示
get-process | select name,cpu | export-csv d:ww.csv -NoTypeInformation

编写函数:
function GMEX {get-help get-member -examples}

function bootini {notepad c:oot.ini} == notepad c:oot.ini


设定当前工作目录:
Set-Location -Path C:Windows -PassThru
get-location

查看驱动器:
get-psdrive -psprovider filesystem | format-table name,root
get-psdrive -name d,e
添加新驱动器:
New-PSDrive -Name Office -PSProvider FileSystem -Root "C:Program FilesMicrosoft OfficeOFFICE11"
remove-psdrive -name office

文件管理:
get-childitem -path d:documents -recurse 递归列出该目录下所有项 -force 显示隐藏项
get-childitem -path c:?.txt 查找只有一个字符的文件
Get-ChildItem -Path C:Windowsx*
-exclude -include

新建文件夹:
new-item -path d:jj -itemtype directory
新建文件:
new-item -path d:jjwt.txt -itemtype file

拆分路径,仅显示文件名:
split-path "c: estlogs*.log" -leaf -resolve

返回唯一值,必须先排序:
$a | sort-object desc | get-unique

分组排序:
get-childitem d:*.* |group-object mode

get-childitem *.* #文件名.扩展名,都是文件
get-childitem * #包含目录,不完全是,注意


删除:
remove-item d:jj -recurse 无提示直接删除
remove-item d:port.txt 文件直接删除,无提示

复制:
copy-item -path d:jj -destination c: 只复制空文件夹jj
copy-item -path d:jj -destination e: -recurse 复制全部内容
copy-item -path d:jj -destination c: -recurse -force 覆盖复制

移动文件夹:
Move-Item -Path C: empNewDirectory -Destination C: -PassThru

查找修改时间晚于2012/10/1的txt文件
get-childitem d:*.txt | where-object {$_.lastwritetime -gt "2012/10/1"}


对test目录下的文件进行过滤,只显示txt格式文件,b开头除外,按lastwritetime降序排列
get-childitem e: est* -include *.txt -exclude b* |sort-object -property lastwritetime -desc

get-childitem e: est* |get-member 查看每个项都具有哪些属性、方法
get-childitem e: est* -name basename|get-member 查看每个项的属性都具有哪些属性、方法


get-childitem e: est* |select name
get-childitem e: est* |select {$_.name.length}
get-childitem e: est* |foreach {$_.name.length}

将name的属性length取出来,并将其作为列与name一同输出
get-childitem e: est* |select name,@{name="changdu";expression={$_.name.length}},lastwritetime |format-table -autosize

排序:使用“_”分割字符串,_前面的为[0],后面的为[1],并使用降序
get-childitem e: est* -include *.txt -exclude b* |sort-object {[int]$_.name.split("_")[1].substring(0,1)} -desc


wmi管理:

Get-WmiObject -List

get-wmiobject -list | where-object {$_.name -like "win32_*"} 查询win32开头的对象

get-wmiobject win32_localtime | get-member 查看属性、方法


Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName win7
Get-WmiObject -Class Win32_OperatingSystem -ComputerName win7
Get-WmiObject Win32_OperatingSystem -ComputerName win7
重命名文件:
Rename-Item -Path C: empNew.Directoryfile1.txt fileOne.txt

get-wmiobject win32_operatingsystem | format-table version,serialnumber -autosize


get-wmiobject win32_operatingsystem | get-member -name *memory* 查询内存相关参数
get-wmiobject win32_operatingsystem | format-list freephysicalmemory,maxprocessmemorysize

筛选:

-eq,-ne,-lt,-le,-gt,-ge,-like,-notlike,-contains,-notcontains

1,2,3,4 | where-object -filterscript{$_ -lt 3} 筛选小于3的数字
1,2,3,4,5,6 | where-object -filterscript{($_ -lt 3) -or ($_ -gt 4)} 筛选小于3或大于4的数字

30000,56798,12432 | foreach-object -process {$_/1024} 对数组中每一个数除以1024

百分比格式化字符串
"{0:p}" -f 0.035655555
小数处理
"{0:#.###}" -f 3.4567 保留3位小数
(3.99999).tostring("f2") 保留2位小数

Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {($_.size)/1024.0/1024.0} 显示分区大小

get-wmiobject win32_logicaldisk | where-object -filterscript {$_.drivetype -eq 3} |format-table deviceid,freespace,size

$size=get-wmiobject win32_logicaldisk | where-object -filterscript {$_.drivetype -eq 3} | foreach-o
bject -process{($_.size)/1024/1024/1024}
$size | foreach-object -process {[int]($_)}
$size | foreach -process {(([int]$_).tostring() + "GB")} tostring()转换为字符串
$size | foreach -process {(($_).tostring("F2") + "GB")} tostring()转换为字符串,四舍五入保留2位小数
$size | foreach -process {("The size is:"+[int]$_+"GB")} 根据左操作数自动将其识别为字符串

Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript { ($_.State -eq "Running") -and ($_.StartMode -eq "Manual") } | Format-Table -Property Name,DisplayName

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName . |
Format-Table deviceid,@{Label="free(GB)"; Expression={$_.freespace/1024/1024/1024}},@{Label="size(GB)"; Expression={$_.size/1024/1024/1024}} -AutoSize | Out-String


显示年份日期:
(get-date).month
get-date -uformat "%Y%m%d" 不需要判断是否大于或小于10月,10日
new-item -path $wt -type dir 创建以当前日期为名的文件夹

单引号不转义,引号内是什么就输出什么;双引号转义,即可将变量通过双引号引起来,然后使用变量内容
tostring()转换为字符串,例:$s.tostring()

查看windows环境变量:
get-childitem env:
$env:computername


输入用户名密码:(powershell中不能直接写入密码)
$pass =get-credential win08r2administrator
get-winevent -logname system -computername win08r2 -Credential $pass | where-object {$_.
id -eq 12 -and $_.timecreated -gt "2012/11/1 8:30:00"}
--查看计算机win08r2的系统日志--时间比较

查看该天的事件日志
get-winevent -logname system -computername win7 | where-object {$_.id -eq 12 -and $_.timecrea
ted.tostring().substring(0,9) -eq "2012/11/2"}

可以保存、清空事件日志
Get-WmiObject -Class Win32_NTEventLogFile

截取字符串,从右往左截取的话可以使用.length
$aa.substring(0,3)

查找扩展名为txt的文件
get-item e: est* |where{$_.name.tostring().split("."[1] -eq "txt"}

只列出扩展名
get-item e: est* |format-table @{name="aa";expression={$_.name.tostring().split(".")[1]}}

获取文件权限:
$j = get-childitem e:wt.txt
通过 $j |get-member 查询可用方法
$j.getaccesscontrol()
$j.SetAccessControl()

设置文件属性:Set-ItemProperty
set-itemproperty -path c:GroupFilesfinal.doc -name IsReadOnly -value $true
get-childitem weekly.txt | set-itemproperty -name IsReadOnly -value $true
Set-ItemProperty e: estwt.txt isreadonly $false (不加$设置不成功,true不加可以设置成功)

measure-command 度量脚本运行时间
send-mailmessage
invoke-command

while循环
$i=0
while($i++ -lt 5)
{ if ($i+1 -eq 3){$i}}

原文地址:https://www.cnblogs.com/cnsealine/p/PowerShell.html