iT邦幫忙

DAY 17
1

強而有力的 Windows PowerShell系列 第 17

使用 Windows PowerShell 找出由 Windows Installer 所安裝的軟體

Windows Installer 是 Microsoft 作業系統中,用於提供安裝、維護與移除軟體的一個引擎。在這次要討論如何使用這個引擎找出所安裝的應用程式。

強而有力的 Windows PowerShell 系列文章列表如下:
http://ithelp.ithome.com.tw/event/ironmanarticle2/id/20005121
一樣先來個簡單的命令,就從查詢透過 Windows Installer 安裝到本機電腦中的應用程式有哪些開始吧:

# 設定變數
$strComputer = "."
$strFile = "c:\installed.txt"

cls
Write-Host "正在查詢透過 Windows Installer 安裝到本機電腦中的應用程式"
Write-Host "請稍候..."

# 將查詢的結果導向到 c:\installed.txt 檔
Get-WmiObject -Class Win32_Product -ComputerName $strComputer |`
 Out-File $strFile

# 檢查檔案是否存在
$fileExist = Test-Path -Path $strFile
if($fileExist -eq "True") {
  # 使用「記事本」開啟 installed.txt 檔
  notepad.exe $strFile
  # 先進入 250 毫秒的睡眠狀態,然後再刪除所產生的檔案
  Start-Sleep -m 250
  del $strFile
}

以下面的指令來說,先取得 Win32_Product 物件,透過管線來找出軟體名稱以 Windows Live 開頭的,接著使用 Format-List 格式化的 cmdlet 並搭配 * 的 Properties 參數值,來逐頁顯示最後的結果:

$strComputer = "."

cls
Write-Host "正在查詢軟體名稱以 Windows Live 開頭的應用程式"
Write-Host "請稍候..."

Write-Host "第 1 種方式"
Get-WmiObject -Class Win32_Product -ComputerName $strComputer | `
  Where-Object -FilterScript {$_.Name -match "^Windows Live*"} | `
  Format-List -Property * | Out-Host -Paging

# 使用 Filter 參數的另外一種寫法
Write-Host "第 2 種方式"
Get-WmiObject -Class Win32_Product -ComputerName $strComputer `
  -Filter "Name like 'Windows Live%'" | `
  Format-List -Property * | Out-Host -Paging

由於上面命令的輸出結果會顯示所有的屬性,因此一般我們只會列出感興趣的屬性,也就是要將 Format-List 的 * Properties 參數值改成所要的屬性:

$strComputer = "."
Write-Host "只列出感興趣的屬性"
Get-WmiObject -Class Win32_Product -ComputerName $strComputer `
  -Filter "Name like 'Windows Live%'" |`
  Format-Table -AutoSize -Property Name, InstallDate, Vendor, Version, IdentifyingNumber |`
  Out-Host -Paging

管理者通常會將伺服器已安裝的應用程式名稱匯出成文字檔,以便日後追蹤之用,則可利用 Format-Wide 這個 cmdlet 來達成該目的:

# 設定變數
$strFile = "c:\installed.txt"

Get-WmiObject -Class Win32_Product | Format-Wide -Column 1 | Out-File $strFile

# 檢查檔案是否存在
if($(Test-Path -Path $strFile) -eq "True") {
  # 使用「記事本」開啟 installed.txt 檔
  notepad.exe $strFile
}

除了透過 Win32_Product 之外,也可使用 Win32_SoftwareFeature。以下面的命令來說,會找出以 Windows Live 帶頭的產品名稱,然後顯示產品名稱、發行商、版本:

# 設定變數
$strComputer = "."

# 篩選符合的產品
$colItems = Get-WmiObject -Class "Win32_SoftwareFeature" `
  -Filter "ProductName like 'Windows Live%'" `
  -Computername $strComputer

# 使用迴圈顯示每個產品的資訊
foreach ($objItem in $colItems) {
      Write-Host "產品名稱:" $objItem.ProductName
      Write-Host "發行商:" $objItem.Vendor
      Write-Host "版本:" $objItem.Version
      Write-Host
}


上一篇
使用 Windows PowerShell 管理服務 - 變更服務的屬性
下一篇
使用 Windows PowerShell 查看已經安裝的 Hotfix
系列文
強而有力的 Windows PowerShell33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言