Search code examples
stringpowershellhashtable

PowerShell: Working with Strings and Hashtables


I have this code:

$passwordsParameters = "sysPassword = 12  &&& testPass = 13 &&& systemPassword = 10"

$parametersList = @($passwordsParameters -split '&&&')

$passwordsTable = @{}


ForEach ($parameter in $parametersList) {
    $splitToKeyValue = @($parameter -split '=')
    $passwordsTable += $passwordsTable = @{
        $splitToKeyValue[0].trim() = $splitToKeyValue[1].trim()
    }
}


ForEach ($pass in $passwordsTable.Keys) {
    if ($passwordsTable[$pass] -ne "") {
        Write-Host "set $pass ="$passwordsTable[$pass]"" 
    } else { 
        Write-Host "A value for the parameter $pass was not entered."
    }
}


# Add-Content "d:\myFile.txt" "set $pass ="$passwordsTable[$pass]""

Which perfectly works when I use Write-Host. But I want to do something like in the comment in line 25. I tried several ways but I always got a static string instead of the values that I get from the Hashtable.

At the end I want to have something like:

set pass1 = 12
set pass2 = 5

in myFile.txt

Any help is appreciated. Thanks!


Solution

  • You could change Write-Host (just prints to a console) to Write-Output ( which passes an object to a pipeline). Write-Output does not print to the console.

    $passwordsParameters = "sysPassword = 12  &&& testPass = 13 &&& systemPassword = 10"
    $parametersList = @($passwordsParameters -split '&&&')
    $passwordsTable = @{}
    
    
    ForEach ($parameter in $parametersList) {
        $splitToKeyValue = @($parameter -split '=')
        $passwordsTable += $passwordsTable = @{
            $splitToKeyValue[0].trim() = $splitToKeyValue[1].trim()
        }
    }
    
    $counter=0
    ForEach ($pass in $passwordsTable.Keys) {
        if ($passwordsTable[$pass] -ne "") {
            $counter++
            Write-Output "set "pass$counter = $passwordsTable[$pass]"`n"  | Add-Content -NoNewline myFile.txt 
        } else { 
            Write-Host "A value for the parameter $pass was not entered."
        }
    }
    

    Output:

    set pass1=10
    set pass2=13
    set pass3=12