PowerShell隨筆1


$a = 1..100

腳本雙擊直接運行:
ftype Microsoft.PowerShellScript.1="C:\WINDOWS\system32\windowspowershell\v1.0\powershell.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:\res.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:\test.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 “root\CIMV2″ 
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\notepad.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:\boot.ini} == notepad c:\boot.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 Files\Microsoft Office\OFFICE11"
remove-psdrive -name office

文件管理:
get-childitem -path d:\documents -recurse 遞歸列出該目錄下所有項 -force 顯示隱藏項
get-childitem -path c:\?.txt 查找只有一個字符的文件
Get-ChildItem -Path C:\Windows\x*
-exclude -include

新建文件夾:
new-item -path d:\jj -itemtype directory
新建文件:
new-item -path d:\jj\wt.txt -itemtype file

拆分路徑,僅顯示文件名:
split-path "c:\test\logs\*.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:\temp\NewDirectory -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:\test\* -include *.txt -exclude b* |sort-object -property lastwritetime -desc

get-childitem e:\test\* |get-member 查看每個項都具有哪些屬性、方法
get-childitem e:\test\* -name basename|get-member 查看每個項的屬性都具有哪些屬性、方法


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

將name的屬性length取出來,並將其作為列與name一同輸出
get-childitem e:\test\* |select name,@{name="changdu";expression={$_.name.length}},lastwritetime |format-table -autosize

排序:使用“_”分割字符串,_前面的為[0],后面的為[1],並使用降序
get-childitem e:\test\* -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:\temp\New.Directory\file1.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 win08r2\administrator
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:\test\* |where{$_.name.tostring().split("."[1] -eq "txt"}

只列出擴展名
get-item e:\test\* |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:\GroupFiles\final.doc -name IsReadOnly -value $true
get-childitem weekly.txt | set-itemproperty -name IsReadOnly -value $true
Set-ItemProperty e:\test\wt.txt isreadonly $false (不加$設置不成功,true不加可以設置成功)

measure-command 度量腳本運行時間
send-mailmessage
invoke-command

 

UNC路徑判斷:
$path = 'filesystem::\\127.0.0.1\c$'
Test-Path -Path $path

 

賦值給變量的同時輸出到控制台
($a=get-process)

 

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

 

#創建域賬戶

$user = [ADSI]"LDAP://CN=test01,OU=oo,OU=Admins,DC=ddv,DC=com"

$a="administrator"
$m = [ADSI]"WinNT://$env:computername/$a"

#重命名計算機
$cs = gw win32_computerysystem -computername $computer
$cs.rename($newName)

 

#查找已連接的網卡
gwmi win32_networkadapter -filter "NetConnectionStatus = 2"

#查找DNS服務器地址

gwmi Win32_NetworkAdapterConfiguration -filter "index = 7"|select DNSServerSearchOrder

gwmi win32_networkadapter -filter "NetConnectionStatus = 2"|foreach {gwmi Win32_NetworkAdapterConfiguration -filter "index = $($_.index)"|select DNSServerSearchOrder}

switch

# `t用於縮進(`thi)
write-host "`tmm"

#路徑包含空格
c:\my `folder\myscript.ps1
&("c:\my folder\myscript.ps1")


#獲得隨機數
([random]5).next()
([random]5).next("1","10")
get-random


#獲得所有注冊到PS的管理單元列表
get-pssnapin -registered

#顯示結果到控制台,並輸出結果到文件
get-process |tee-object d:\test.txt

#顯示16進制
"{0:x}" -f 1234

#未聲明某個變量時顯示錯誤信息
將 Set-PSDebug-strict 放在腳本中任何位置

將 $erroractionpreference=SilentlyContinue 放在腳本開頭,可以讓PS忽略錯誤並繼續執行其余代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM