首页 > 解决方案 > 从 pester 中的属性文件中读取值

问题描述

我想使用 pester 框架从 powershell 中的属性文件中读取数据,但遇到错误。

属性文件:

vmsize1='Standard_D3_V2'
vmsize2='Standard_DS1_V2'

代码:

 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"
        }
    }

输出:

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

请帮我解决这个问题!

标签: powershellproperties-filepester

解决方案


这可以通过稍微更改代码来实现。

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

然而,这不是最好的方法,我建议使用 JSON,因为我发现这更容易在 PowerShell 中序列化。将此保存为您的properties.json文件

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

你的代码看起来像

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

由于 JSON 的刚性,这种方式将更容易更新,并且还允许您在将来随着代码的扩展添加额外的属性。


推荐阅读