Search code examples
powershellproperties-filepester

Read the values from properties file in pester


I want to read the data from properties file in powershell using pester framework, but facing an error.

Properties file:

vmsize1='Standard_D3_V2'
vmsize2='Standard_DS1_V2'

Code:

 Context "VIRTUAL MACHINE" {

        $file_content = get-content "$here/properties.txt" -raw     
        $configuration = ConvertFrom-String($file_content)
        $environment = $configuration.'vmsize1' 

        It "CHECKING THE SIZE OF VM" {
            $environment | Should -Be "Standard_D3_V2"
        }
    }

Output:

Context VIRTUAL MACHINE
      [-] CHECKING THE SIZE OF VM 78ms
        Expected 'Standard_D3_V2', but got $null.
        694:             $environment | Should -Be "Standard_D3_V2"

Please help me to resolve this issue!


Solution

  • This is achievable by changing your code slightly.

    $configuration = ConvertFrom-StringData(get-content "$here/properties.txt" -raw)
    $configuration.vmsize1
    

    However this is not the nicest way and I would suggest using JSON as I have found this much easier to serialize in PowerShell. Save this as your properties.json file

    {
        "vm1": {
            "size": "Standard_D3_V2"
        },
        "vm2": {
            "size": "Standard_D3_V2"
        }
    }
    

    your code would look like

    $fileContent = Get-Content "$here/properties.json" -raw
    $configuration = ConvertFrom-Json $fileContent
    $configuration.vm1.size
    

    This way would make it easier to update due to the rigidness of JSON and would also allow you to add extra properties in the future as your code expands.