使用Powershell读取Excel文件

时间:2014-06-02 09:02:00

标签: excel powershell foreach

我有一个excel服务器列表,其中D列是主机名和列F区域(如dev,int,prd)。现在我想用PowerShell和打印输出每个具有区域dev的主机名来阅读这个excelfile。我需要改变什么?

$FilePath = "C:\serverlist.xlsx"
$SheetName = "serverlist"
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($FilePath)
$WorkSheet = $WorkBook.sheets.item($SheetName)


$Range = $WorkSheet.Range("F2:F150").Text

Foreach ($cell in $Range) {

    If ($cell -like "dev") {

        Write-Host "hostname from  Column D"

    }

}

1 个答案:

答案 0 :(得分:2)

将您的电子表格另存为CSV,您将能够更快地处理列表。然后,您可以使用以下代码,将-Header之后的值更改为与您相关的列名:

$FilePath = "C:\serverlist.csv"
$serverList = Import-Csv $FilePath 
    -Header "ColumnA","ColumnB","ColumnC","HostName","Area"
$serverList | where {$_.Area -like"dev" } | Select-Object HostName