如何以 PowerShell 收集與監控 SQL Serverdownload.microsoft.com › download › 5 › 9 › E...
Transcript of 如何以 PowerShell 收集與監控 SQL Serverdownload.microsoft.com › download › 5 › 9 › E...
胡百敬集英信誠合夥顧問http://byronhu.wordpress.com
以 PowerShell 完成營運管理與監控
PowerShell 背景工作
PowerShell 流程
遠端存取
CIM 與 WMI
大綱
非同步地以背景執行緒執行,讓前景立刻回應使用者,除非採用排程工作,否則只活在當下的 Session
部分 cmdlet 有 AsJob 參數直接背景執行
使用 Start-Job 啟動背景執行ScriptBlock
FilePath
使用 Get-Job 查看工作的執行狀態
使用 Receive-Job 接收工作的輸出
使用 Remove-Job 刪除工作
使用 Stop-Job 停止異常的工作
使用 Wait-Job 等待工作執行完畢
背景工作
使用 Receive-Job取得指定的一個以上之 Job 結果
使用 –ID 參數,以 ID 指定 Job
使用 –Name 參數,以名稱指定 Job
加上 –Keep 參數,將執行結果保留在記憶體
從 Parent job 取結果,將會取得所有 child job 的結果
取得工作的結果
讓 PowerShell 的背景工作依特定的條件觸發,透過 Windows Task Schedule 控管,但相關定義存在個人目錄下
支援多種觸發條件Once、AtLogon、AtStartup、Daily、Weekly
PSScheduledJob 模組包含 16 個 cmdlet*-JobTrigger 定義觸發條件
*-ScheduledJob 註冊、解除及變更 Scheduled job
*-ScheduledJobOption 進行進階設定
*-Job 接收執行結果
需至少 WMF 3.0
排程工作(Scheduled Job)
排程工作(Scheduled Job)
# Schedule Job 是跨 PowerShell session 的,因為是透過 Windows 排程叫起來# -RepetitionInterval 最小是一分鐘$Trigger = New-JobTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minute 1) -RepetitionDuration (New-TimeSpan -Hours 1)Register-ScheduledJob -Name SchJobGetPerformanceCounter -Trigger $Trigger -FilePath .\CollectPerformanceCounter.ps1Get-ScheduledJob
UnRegister-ScheduledJob -Name SchJobGetPerformanceCounter
#相關定義存在這個目錄下,AUnRegister-ScheduledJob 會自動清掉其下對應的子目錄cd "$home\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs"
PowerShell
Windows Workflow
Foundation
PowerShell Workflow
PowerShell Workflow
• 以 PowerShell 定義與執行長時間的流程
• 以熟悉的 PowerShell 語法撰寫,編譯成 Windows Workflow
XAML
• 善用 PowerShell modules,
scripts
• 可以平行或循序地執行• 可中斷、暫停、重啟執行
Get-Command <Workflow名稱> | select -ExpandProperty XamlDefinition |Out-file .\ <Workflow名稱>.xaml
PowerShell Workflow 相關指令
• Workflow
• Parallel
• Foreach –Parallel
• Sequence
• InlineScript
• Checkpoint-Workflow
• Suspend-Workflow
在 Workflow 內必須要 By Name 傳遞參數
1
workflow foo {$numbers = @(1, 2, 3)$numbers | Where-Object { $_ -
eq 1 }}
Where-Object : 參數集無法使用指定的具名參數解析。
+ CategoryInfo : InvalidArgument: (:) [Where-Object],ParentContainsErrorRecordException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.WhereObjectCommand
+ PSComputerName : [localhost]
$numbers = @(1, 2, 3)$numbers | Where-Object { $_ -eq 1}
PowerShell Workflow 實作規範
workflow foo {$numbers = @(1, 2, 3)
$numbers | Where-Object -FilterScript { $_ -eq 1 }
}
1
PowerShell Workflow 實作規範
在 Workflow 內必須要 By Name 傳遞參數
$date = Get-Date$date.AddDays(1)
2015年11月22日15:07:51
workflow bar {$date = Get-Date$date.AddDays(1)
}
位於線路:3 字元:5
+ $date.AddDays(1)
+ ~~~~~~~~~~~~~~~~
Windows PowerShell 工作流程中不支援方法叫用。若要使用 .NET 指令碼,請將命令放入內嵌指令碼中:
InlineScript { <commands> }。+ CategoryInfo : ParserError: (:) [],
ParentContainsErrorRecordException
+ FullyQualifiedErrorId :
MethodInvocationNotSupported
在 Workflow 內物件必須在 Script Block 內叫用方法
PowerShell Workflow 實作規範
2015年11月22日 15:10:03
workflow bar {
InlineScript {
$date = Get-Date$date.AddDays(1)
}}
PowerShell Workflow 實作規範
在 Workflow 內物件必須在 Script Block 內叫用方法
以 Windows Data Protection API(DPAPI)來保護資料,透過登入帳號來加密資料,不同帳號解不開對方加密的資料
ConvertTo-SecureString:將字串轉成 SecureString 物件
ConvertFrom-SecureString:將 SecureString 物件轉成字串
SecureString
$secure=Read-Host -AsSecureString -Prompt "Password"$secure | Export-Clixml -Path .\a.xmlGet-Content .\a.xml#取L出 SecureString 的內容$s=Import-Clixml .\a.xml[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($s))
使用具有 -ComputerName 參數的 cmdletGet-Help * -Parameter ComputerName
不同的 cmdlet 可能使用不同的方式通訊
透過 RPC/DCOM 通訊Windows 2000(含以上)的 Windows 作業系統
Windows XP(含以上)防火牆需允許輸入的遠端系統管理例外
透過 WinRM 通訊Windows 2008 R2/Win7 (含以上)或已更新 KB968930 的 Windows XP/2003/Vista/2008
設定 WinRM
Windows Server 2012 預設已 Ready
遠端管理
PSRemoting的架構(WinRM)
被管理的遠端電腦
管理者所使用的電腦Windows
PowerShell.exe
Wsmprovhost.exe
端點:PowerShell
端點:PowerShell
Windows Remote Management(WinRM) 服務
Listener (HTTP)
WS-MAN(HTTP(s)) 網路通訊
Wsmprovhost.exe
使用命令提示字元WinRM quickconfig
使用 Windows PowerShellSet-WSManQuickConfig
Enable-PSRemoting
使用群組原則電腦設定→原則→系統管理範本→Windows 元件→Windows 遠端管理→WinRM 服務→允許透過 WinRM 進行遠端伺服器管理(允許自動設定接聽程式)
Windows 防火牆:TCP 5985 及 5986 例外
系統服務:Windows Remote Management
設定及啟用WinRM
Windows Server 2012 以前,需要透過 Enable-PSRemoting 啟動
• 安全、強化的遠端 console
• 在工作群組中,可配合
–Credential 參數設定身分
• 可對多台機器平行運算
遠端存取
Invoke-Command -ComputerName n1,n2,n3 -ScriptBlock `{Get-EventLog -LogName Application `-EntryType Error -Newest 3}
Invoke-Command -ScriptBlock {restart-Computer} -ComputerName "n2","n3"
使用 PSSessionCmdlet 沒有 -ComputerName 參數可用時
雙方皆需有 PowerShell 2.0/3.0 及 WinRM2.0/3.0New-PSSession
Enter-PSSession
Exit-PSSession
Get-PSSession
Remove-PSSession
Disconnect-PSSession
Connect-PSSession
或使用 Invoke-Command
遠端執行命令(透過WinRM )
當傳輸網路失靈或故障時, Remote session 在 4 分鐘內仍繼續保留在 “Opened" 狀態
4 分鐘後, Remote session 將自動轉變為"Disconnected" 狀態
即使 session 處於 "Disconnected" 狀態, 持續的命令與工作仍能繼續執行
當網路連通後,用戶端可重新連接已中斷的session (使用 Connect-PSSession)
用戶端也可手動對 Remote session 進行Disconnect (使用 Disconnect-PSSession)
需至少 WMF 3.0
PowerShell 的 Session 連通能力
Install-WindowsFeature –VName WindowsPowerShellWebAccess -ComputerNameServerCore -IncludeManagementTools –Restart
Install-PswaWebApplication -UseTestCertificate #沒有申請憑證,只好用自建的
#無法直接透過遠端 Session 執行,要直接登入到該機器上執行以下語法Add-PswaAuthorizationRule –VUserName i\Administrator -ComputerNameServerCore -ConfigurationName *
透過 PowerShell Web Access 存取
相關注意事項
#若不要啟動 SSLSet-Item WSMan:\localhost\Client\TrustedHosts 'win2016,ServerCore'
#傳遞參數,2.0 的語法$Log = 'Application'$Quantity = 10Invoke-Command –Computer win2016 –ScriptBlock {Param($x,$y) Get-EventLog –LogName $x –Newest $y} –ArgumentList $Log,$Quantity -Credential $credential#3.0 後的語法Invoke-Command –Computer win2016 –ScriptBlock {Get-EventLog –LogName$Using:Log –Newest $Using:Quantity} -Credential $credential
Windows 作業系統遵循 Distributed Management Task Force(DMTF) 的 Common Information Model(CIM) 標準,實作Windows Management Instrumentation(WMI )介面,提供查詢與修改各種軟硬體資訊的檢視與方法
在 Repository 內存有描述各種電腦物件的 Class,你電腦內的物件或執行的程式是對應 Class 的 Instance
透過 Instance 的屬性方法管理電腦上的物件
PS 3.0 後建議採用
新實作的 CIM
WMI 與 CIM
架構與技術
Repository
WMI WinRM
DCOM
WS-MAN
早期(WMI
)
新技術(CIM)
Get-WmiObject -Namespace root\cimv2 -List | where Name -Like win32_o* | Sort NameGet-CimClass –Namespace root\CIMv2 -ClassName win32_o* | Sort CimClassName
Get-WmiObject -Class Win32_OperatingSystemGet-CimInstance -ClassName Win32_OperatingSystem
Get-WmiObject –Class Win32_LogicalDisk –Filter "DriveType=3"Get-CimInstance –ClassName Win32_LogicalDisk –Filter "DriveType=3"
WMI/CIM名詞說明
WMI/CIM 說明 實例
Namespace
(名稱空間)相關類別的集合 Root\cimv2
Class (類別)物件的藍圖可進行管理的種類
Win32_
LogicalDisk
Instance(執行個體)物件的實體同一類別可能同時有多個
C:
Property (屬性)物件的特性在 WMI 中多數是唯讀的
FileSystem
Method (方法) 物件能執行的動作 chkdsk
列舉WMI 類別
Get-WMIObject –List Server/Workstation
Windows PowerShell
List of WMI Classes
Server/Workstation
Get-WMIObject –namespace <name> –List -ComputerName
取得特定 Class 的所有 InstancesGet-WmiObject <Class 名>
Get-WmiObject –Query "select * From < Class 名>"
可配合 –ComputerName 進行遠端操作
取得特定 Class 的特定 InstanceGet-WmiObject <Class 名> -Filter “<屬性名>=‘<值>’”
使用WMI
列出指定類別執行個體的屬性
列出指定類別執行個體的方法
列舉執行個體的屬性與方法
$objSvc= Get-WmiObject win32_service -filter "name = 'SQLBrowser'"Get-Member -InputObject $objSvc -MemberType property
Get-Member -InputObject $objSvc -MemberType method | Selectname,definition | Out-GridView
列舉本電腦上的 NamespaceGet-CimInstance -Namespace Root -ClassName __NameSpace
列舉類別Get-CimClass
取得特定 Class 的所有 InstancesGet-CimInstance <Class 名>
可配合 –ComputerName 進行遠端操作
取得特定 Class 的特定 InstanceGet-CimInstance <Class 名> -Filter “<屬性名>=‘<值>’”
使用 CIM
WMI 或 CIM?
CIM WMI
需要 WMF 2.0+ 是* WMF Not
required
是否需要啟動 Remoting 是* 否
跨平台的能力,例如支援非 Windows 為基礎的系統 是 否
支援以會談為基礎的連接 是 否
支援 ad-hoc 為基礎的連接 是 是
支援 Microsoft Windows XP 及其後的版本 是 是
支援 Microsoft Windows Server 2003 及其後的版本 是 是
支援 Microsoft Windows NT 4.0 及其後的版本 * 是
需要開 Remote Administration firewall * 是
*當 CIM 命令使用 CIMSession 去建立 DCOM 連接時, CIM 與 WMI 有相同的支援
參考資源
http://www.microsoftvirtualacademy.com/training-topics/management_security_topic_page_en
Windows PowerShell Unplugged with Jeffrey Snoverhttp://channel9.msdn.com/events/TechEd/Europe/2014/CDP-B357
Eight Steps to Effective SQL Server Monitoringhttps://www.simple-talk.com/sql/database-administration/eight-steps-to-effective-sql-server-monitoring/
透過 PowerShell 部署 SSIShttp://blogs.lessthandot.com/index.php/datamgmt/dbadmin/mssqlserveradmin/ssis-deployment-with-powershell-adding/
PowerShell 免費電子書http://powershell.org/wp/ebooks