1.文件夾長度返回1
$folder = Get-Item c:\Windows
$folder.Length
$Host.length
2.後臺執行任務
$code = {Get-Content D:\1.txt } #定義任務
$job = Start-Job -ScriptBlock $code #執行任務
$alljobs = Wait-Job $job #等待任務完成
$result = Receive-Job $alljobs #接受任務
Remove-Job -Job $alljobs #刪除任務
Write-Host $result #輸出任務結果
後臺任務耗時時間長,儘量使用管道篩選自己想要的結果
3.按多列排序
get-service | sort-object -property @{Expression="Status";Descending=$true}, @{Expression="DisplayName";Descending=$false}
4.快速輸出相同行
Measure-Command {
$text = "Hello"
for ($x=0; $x -lt 10000; $x++)
{
$text += "status $x"
}
$text
}
Measure-Command{
$obj = New-Object -TypeName System.Text.StringBuilder
$null = $obj.Append("Hello");
for($x=0;$x -lt 10000;$x++)
{
$null = $obj.Append("status $x");
}
$obj
}
5.設置參數的默認值
使用 $PSDefaultParameterValues.Add('*:Path', 'c:\Windows') 定義當調用帶參數path的函數時默認的路徑是c:\windows
可以使用函數名代替*,表示只是在調用這個函數時默認參數生效
$PSDefaultParameterValues.Add('Get-WmiObject:ComputerName', 'server12')
刪除自己定義的默認參數
$PSDefaultParameterValues.Clear()
6.監聽windows按鍵事件
7.開啓powershell遠程
Powershell遠程管理
被遠程機器上執行
Enable-PSRemoting -Force
本機執行
Enable-PSRemoting -Force
Set-Item -Path WSMan:\localhost\client\trustedhosts -Value * -Force
8.設置命令執行超時
function Invoke-TimeoutCommand
{
param(
[int]$timeout,
[ScriptBlock] $ScriptBlock
)
$job = Start-Job -ScriptBlock $ScriptBlock
$job | Wait-Job -Timeout $timeout
if($job.State -ne 'finish')
{
Write-Warning 'timeout'
$job|Stop-Job|Remove-Job
return $null
}
else{
return $job | Receive-Job
}
}
Invoke-TimeoutCommand -Timeout 10 -ScriptBlock {
ping pstips.net -n 500
}
9.設置excel cvs編碼爲utf8
$Path = 'c:\temp\somedata.csv'
(Get-Content -Path $Path) | Set-Content -Path $Path -Encoding UTF8
10.異常捕獲
try
{
1/0
}
catch [DivideByZeroException]
{
Write-Host "Divide by zero exception"
}
catch [System.Net.WebException],[System.Exception]
{
Write-Host "Other exception"
}
finally
{
Write-Host "cleaning up ..."
}
# 1/0
#$Error[0] | fl * -Force
查看到異常類型,然後捕獲 -->標記,沒有的爲複製異常
11.兩個時間段內的時間
$startdate = Get-Date
$end = Get-Date "2014-09-12"
$difference = New-TimeSpan -Start $startdate -End $end
#計算還多少天
$difference.Days
$days = [System.Math]::Ceiling($difference.TotalDays)+1
$workdays = 1..$days | ForEach-Object{
$startdate
$startdate=$startdate.AddDays(1)
}| Where-Object{$_.DayOfWeek -gt 0 -and $_.DayOfWeek -lt 6} | Measure-Object |Select-Object -ExpandProperty Count
12.文件路徑中出現[],路徑不識別
13.複製過去5條命令
Get-History -Count 5 | Select-Object -ExpandProperty CommandLine | clip.exe
14.獲取之前執行的命令
function Get-MyGeniusInput
{
param
(
$Count,
$Minute = 10000
)
$cutoff = (Get-Date).AddMinutes(-$Minute)
$null = $PSBoundParameters.Remove('Minute')
$result = Get-History @PSBoundParameters |
Where-Object { $_.StartExecutionTime -gt $cutoff } |
Select-Object -ExpandProperty CommandLine
$count = $result.Count
$result | clip.exe
Write-Warning "Copied $count command lines to the clipboard!"
}
Get-MyGeniusInput -Minute 25
15.加載函數
. "$PSScriptRoot\library1.ps1"