Anas Hamra
Anas Hamra

Reputation: 345

Using .TXT file as input variables - PowerShell

I have the following script that I have to input manually.

However, I am looking to provide a text file along with the script to read the inputs from there.

For example, I have two variable below:

$RedirectURIs = $CustomerWebUIurl
$appURI = $CustomerSamlIssuerID

Where I need to pull the following values from text file

$CustomerWebUIurl
$CustomerSamlIssuerID

Screenshot of the config file text

So when I add

$configFile = Get-Content -Path .\config.conf

What else I can use/add to define those two lines in the text file to the two variables I have in the script?

Thanks for the help!

Upvotes: 2

Views: 2136

Answers (2)

mklement0
mklement0

Reputation: 437988

Your config file is in a format that the ConvertFrom-StringData can process, which converts lines of =-separated key-value pairs into hashtables:

# Create a sample config.conf file
@'
$CustomerWebUIurl = http://example.org&1
$CustomerSamlIssuerID = http://example.org&2
'@ > ./config.conf

# Load the key-value pairs from ./config.conf into a hashtable:
$config = ConvertFrom-StringData (Get-Content -Raw ./config.conf)

# Output the resulting hashtable
$config

The above yields:

Name                           Value
----                           -----
$CustomerWebUIurl              http://example.org&1
$CustomerSamlIssuerID          http://example.org&2

That is, $config now contains a hashtable with entries whose key names are - verbatim - $CustomerWebUIurl and $CustomerSamlIssuerID, which you can access as follows: $config.'$CustomerWebUIurl' and $config.'$CustomerSamlIssuerID'

The need to quote the keys on access is somewhat cumbersome, and the fact that the key names start with $ can be confusing, so I suggest defining your config-file entries without a leading $.

If you have no control over the config file, you can work around the issue as follows:

# Trim the leading '$' from the key names before converting to a hashtable:
$config = ConvertFrom-StringData ((Get-Content -Raw .\config.conf) -replace '(?m)^\$')

Now you can access the entries more conveniently as $config.CustomerWebUIurl and $config.CustomerSamlIssuerID

Upvotes: 1

Anas Hamra
Anas Hamra

Reputation: 345

I just figured out how, to use simply array:

Here is the answer script

$configFile = Get-Content -Path .\config.conf

$configFile.GetType()
$configFile.Count
$configFile
$CustomerWebUIurl = $configFile[0]
$CustomerWebUIurl

$CustomerSamlIssuerID = $configFile[1]
$CustomerSamlIssuerID

Upvotes: 0

Related Questions