Home > database >  get all the env variable in powershell
get all the env variable in powershell

Time:10-22

I want to convert the below code from bash to PowerShell but I am not sure how I can get list of variable. would you mind help me? this code will find all the variable in shell with prefix of conf__ and then add them as parameters.

 params=(
    --master "$MASTER"
  )

 for var_name in "${!conf__@}"; 
 do 
       key=${var_name#conf__}; 
       key=${key//_/.}; 
       value=${!var_name}; 
       params =( --conf "$key=$value" ); 
 done
 echo "myexecutable" "${params[@]}"

so far I could convert this:

$params = @(
    '--master "$MASTER"'
)

ForEach-Object gci env: | where name -like 'Pro*' {
# but how handle this part?
}

CodePudding user response:

# Create two-element array.
# Note: 
#  * 'MASTER' is assumed to be the name of an *environment* variable too.
$params = '--master', $env:MASTER

# Append to the array.
$params  = 
  Get-Item Env:conf__* | # All env. vars. prefixed with "conf__"
  ForEach-Object {       # Process each
    '--conf'             # Verbatim new array element.
    # Calculated new array element:
    # Construct a "<key>=<value>" string for the env var. at hand.
    # To construct the key, strip the "conf__" prefix and replace any 
    # "_" chars. with "."
    '{0}={1}' -f ($_.Name -replace '^conf__' -replace '_', '.'), $_.Value
  }

To pass the resulting array as individual arguments to an external program, say foo, pass it as-is:

foo $params

Note: You may also use @params, i.e. use splatting, though for external programs $params works too.

  • Related