Pages - Menu

2019年7月23日 星期二

[PowerShell]初學筆記 - Part III

1.左過濾,盡可能把過路條件放在左側或靠近命令行的開始部分。越早過濾越能減輕其他Cmdlet命令的工作。

Get-Service –name e*,*x*


2.條件判斷
表達式 中文
-eq 等於
-ne 不等於
-ge 大於或等於
-le 小於或等於
-gt 大於
-lt 小於
-and 而且
-or
-not 取值的相反
-like
-nolike
-clike
可接受* ,做查詢
忽略大小寫
區分大小寫
-match正則表達式
(5 –gt 10) –and (10 –gt 100) 返回false



3. -filter 是一個位置參數,通常可不寫,別名為where
4.   $_ 代表目前的管線物件(Pipeline object),表示前一個Cmdlet指令下產生的資料

Get-Service | Where { $_.Status –eq ‘Running’}

Powershell V3 新的寫法

Get-Servier | Where Status –eq  ‘Running’

5.使用Get-help Get-Service –Full 來判斷參數是否可以接受pipline輸入,
輸入的方式為ByValue 或 ByPropertyName
6.如果不能使用Pipeline來傳遞參數,就改使用小括號,來做優先執行。

Get-WMIObject -Class Win32_BIOS -ComputerName 
(Get-Content .\computers.txt)

7.
select 是一個別名(可用get-help select查詢)
Select –Property Name這種命令只會返回一個Name的屬性
Select –Expand Name
8.格式化表格
  a. 選擇想要的欄位


Get-Service | Format-Table -Property *
Get-Service | Format-Table -Property Name,status

  b.群組  -groupBy

Get-Service | Sort-Object status |Format-Table -Property name,status -GroupBy status


C.顯示成 摘要 –wrap


#Get-Service | Sort-Object status |Format-Table -Property name,displayname,status -GroupBy status -AutoSize –wrap

9.自定義欄位
轉成整數


Get-Process |   Format-Table Name,  @{n='VM(MB)';e={$_.VM / 1MB -as [int]}} –autosize

小數點第二位,並靠右對齊


Get-Process |  Format-Table Name,  @{n='VM(MB)';e={$_.VM};formatstring='F2';align='right'} –autosize
MSDN-Formatting Types

10.過濾對象的Pipeline
-filter的別名是where


Get-Service | Where-Object -filter { $_.Status -eq 'Running' }

等同


Get-Service | Where { $_.Status -eq 'Running' }

$_只能在查找特定位置用,請看(4),可使用的參數,可利用gm查詢


get-service | gm

查詢別名,多利用get-help 或 help
11.寫powershell時
中間用 | (管道符號結尾)換行的話,
powershell會出現提示字元(>>),powershell會等你輸入更多的命令,
直到以大括號、引號,和括號結尾為止;或是直接輸入兩次Enter
(Powershell ISE 無法以此方式執行)


Get-Process |  
Format-Table Name,  
@{n='VM(MB)';e={$_.VM / 1MB -as [int]}} –autosize




12.拆解題目
計算正在使用記憶體的十大程式,並加總
a.取得程式列表
b.排除powershell
c.按照記憶體使用量排序
d.只留前10個或後10個
e.把記憶體使用量相加


Get-Process | Where-Object -filter { $_.Name -notlike 'powerShell*' }|
Sort VM -descending | Select -first 10 |
Measure-Object -property VM -sum

沒有留言:

張貼留言