Daily tips-7月

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"







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章