2016-09-18 56 views
0

我有2个TXT文件:如何在文本文件中VLOOKUP使用PowerShell

的ConfigurationFile:

ABC_LKC_FW_PATH: \\PathToABCFolder 
QWE_LKC_MW_PATH: \\PathToQWEFolder 
DEF_BKC_FW_PATH: \\PathToDEFFolder 
ERT_BKC_MW_PATH: \\PathToERTcFolder

和其他与参数

ChoosenConfig:

ABC_LKC_FW_PATH 
ERT_BKC_MW_PATH

我的脚本读取并解析配置文件以获取名称和值。 我需要从ChoosenConfig文件读取并使用ConfigurationFile中的字符串值。

不知道该怎么办呢?

脚本至今:

$IniFile_NME = "$SmokeTestFolder\SanityTests\Config\ConfigToParse.ini" 
dir $IniFile_NME 

$InputFile = [System.IO.File]::OpenText("$IniFile_NME") 

while ($InputRecord = $InputFile.ReadLine()) { 
    # Display the current record 
    Write-Host "`$InputRecord=$InputRecord" 
    Write-Host "" 

    # Determine the position of the sign (:) 
    $Pos = $InputRecord.IndexOf(':') 
    Write-Host "`$Pos=$Pos" 

    # Determine the length of the record 
    $Len = $InputRecord.Length 
    Write-Host "`$Len=$Len" 

    # Parse the record 
    $Variable_NME = $InputRecord.Substring(0, $Pos) 
    $VariableValue_STR = $InputRecord.Substring($Pos + 1, $Len -$Pos -1).ToUpper() 

    Write-Host "`$Variable_NME=$Variable_NME" 
    Write-Host "`$VariableValue_STR=$VariableValue_STR" 

    # Create a new variable based on the parsed information 
    New-Variable -Force -Name $Variable_NME -Value $VariableValue_STR.Trim() 

    # new-variable -name $Variable_NME -value $VariableValue_STR 
    Get-Variable -Name $Variable_NME 
} 
$InputFile.Close() 

回答

0

当你需要使用其它的价值选择的数据结构是一个hashtable查找某个值。分裂您在冒号后面的空格(:\s*)输入,并填补了哈希表是这样的:

$configs = @{} 
Get-Content $IniFile_NME | ForEach-Object { 
    $key, $value = $_ -split ':\s*' 
    $configs[$key] = $value 
} 

另一种选择是使用ConvertFrom-StringData。为此,您需要将INI文件的内容转换为单个字符串,其中键和值由=而不是:分隔。

$configs = (Get-Content $IniFile_NME -Raw) -replace ':\s*', '=' | 
      ConvertFrom-StringData 

使用Get-Content $IniFile_NME | Out-String而不是Get-Content $IniFile_NME -Raw如果你还在使用PowerShell v2或更早。

一旦你有一个哈希表中的数据,你可以看看你的configs像这样:

Get-Content $chosenConfigsFile | ForEach-Object { $configs[$_] } 
相关问题