从文本文件加载变量,如果哈希表中存在键,则使用键值

时间:2018-07-12 14:17:06

标签: powershell hashtable

我正在尝试创建一个脚本,其中变量在PowerShell脚本之外。这只是一个文本文件。在该文件中,我们定义服务器名称,组名称及其值。组名意味着主机的主机名中包含这些字符串。

主机名具有较高的优先级,而组名具有最低的优先级。如果都不存在,则存在一个默认值(在ps脚本内部)。

以下elseif条件不适用于我,我已经尝试了许多其他方法,但无法使其正常工作。

    elseif ($MachineName.Contains("$var.key")) { # Doesn't work. What can be used here?
    $foldername = ("$var.value")             # Doesn't work. What can be used here?
}

vars.txt的内容:

    #Groups
    DB=folder7

    #Hostnames
    server_JIRA_001=folder3
    server_DB_001=folder5
    server_DB_005=folder6

如果主机名是server_DB_006,它将使用值“ folder7”,因为其主机名中带有“ DB”,但是如果主机名是server_DB_005,则它将使用值“ folder6”

script.ps1的内容

    $MachineName = "server_DB_006"
    $var = (Get-Content "c:\Users\user\Desktop\vars.txt" -Raw | ConvertFrom-StringData) 

    if ($var.$MachineName -ne  $null) {
    # if hostname exists, then use its var.value
    $foldername = ($var.$MachineName)          # returns value of $var.hostname
    } elseif ($MachineName.Contains("$var.key")) { # Doesn't work. What can be used here? 
    # if no hostname defined, then search for group name and use its var.value
    $foldername = ("$var.value")                # Doesn't work. What can be used here? 
    } else {
    foldername = "default_folder"
    }

1 个答案:

答案 0 :(得分:0)

因此,您可以创建一个函数,如果字符串包含键名,该函数将带回键名。它遍历键并检查$ Text以查看是否包含键文本,否则返回false。

function StringContainsHashTableKey(){
    PARAM(
        [string]$Text,
        [hashtable]$HashTable
    )

    foreach($i in $Hashtable.Keys.GetEnumerator()){
        if($Text -like "*$i*" ){
            return $i
        }
    }
    return $false
}

$Var = Get-Content "c:\Users\user\Desktop\vars.txt" -Raw | ConvertFrom-StringData

$MachineName = "server_DB_006"

$KeyMatch = StringContainsHashTableKey -Text $MachineName -HashTable $Var

if ($var.$MachineName -ne  $null) { #if hostname exists, then use its var.value
    $foldername = ($var.$MachineName) # returns value of $var.hostname
} 
# If no hostname defined, then search for group name and use its var.value
Elseif ($KeyMatch -ne $false) { # Doesn't work. What can be used here? 
    $foldername = $var.$KeyMatch
}
Else {
    $foldername = "default_folder"
}

$foldername