在powershell中读取CSV并返回等效数据

时间:2015-05-06 14:25:26

标签: powershell csv

我已阅读Read a Csv file with powershell and capture corresponding data并且已经能够汇总一些代码,但它没有给我我想要的东西,我试图让它读取CSV,在第1列找到服务器,在Internet Explorer中的第2列中打开IP地址。

function Open-RAC
{
param
    (
    [Parameter(Mandatory = $true)]
    [string]$ComputerName
)

$ServerName = @()
$IMM = @()

Import-Csv C:\Scripts\ComputerList\IMMs.CSV |
ForEach-Object {
    $ServerName += $_.ServerName
    $IMM += $_.IMM
}

$inputNumber = $ComputerName#Read-Host -Prompt "Short Server Name"

if ($ServerName -contains $inputNumber)
{
    Write-Host "DRAC Exist"
    Write-Host "Servername : $inputNumber"
    $Where = [array]::IndexOf($ServerName, $inputNumber)
    Write-Host "Where : $Where"
    Write-Host "DRAC IP Address: " $IMM[$Where]
    $URL = $IMM[$Where]
    Write-Host "$URL"
    $IE = new-object -com internetexplorer.application
    $IE.navigate2("http:\\$URL")
    $IE.visible = $true
}
Else
{
    Write-Host " That server does not have a DRAC or you mistyped the server name"
}

然而,这并没有给我正确的IP地址,但无论CSV中的最后一个是什么。

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

从CSV中构建hashtable

$drac = @{}
Import-Csv C:\Scripts\ComputerList\IMMs.CSV | ForEach-Object {
  $drac[$_.ServerName] = $_.IMM
}

然后您可以像这样连接到DRAC:

if ($drac.Contains($ServerName)) {
  Write-Host "Servername : $ServerName"
  $URL = $drac[$ServerName]
  $IE = New-Object -COM 'InternetExplorer.Application'
  $IE.Navigate2("http:\\$URL")
  $IE.Visible = $true
}

答案 1 :(得分:0)

[array] :: IndexOf函数区分大小写,如果输入与.csv中找到的servername不同,则返回-1。您需要找到一种方法使IndexOf不区分大小写(我正在寻找并在我找到它时会更新)或规范化输入以使其与.csv中的匹配。