如何通过PowerShell的Get-Content提取tfvar文件单个变量值
提取Terraform tfvar文件中指定变量的值(PowerShell实现)
你当前是把整个tfvar文件读成了一个字符串,无法直接通过.属性名的方式访问变量值,需要通过字符串匹配来提取目标变量resource_group_postfix的内容,以下是两种可行的实现方式:
方法1:正则表达式匹配(高效简洁)
直接对整个文件内容字符串进行正则匹配,快速捕获目标变量的值:
# 读取tfvar文件内容为字符串 $product_list = Get-Content "../templates/variables/dev.terraform.tfvars" -Raw # 匹配resource_group_postfix变量的值 if ($product_list -match 'resource_group_postfix\s*=\s*"([^"]+)"') { $resourceGroupPostfix = $matches[1] Write-Host "resource_group_postfix的值: $resourceGroupPostfix" } else { Write-Host "未找到resource_group_postfix变量" }
方法2:逐行遍历处理(更直观)
逐行读取文件内容,跳过注释和空行后匹配目标变量:
# 逐行读取tfvar文件 $product_list = Get-Content "../templates/variables/dev.terraform.tfvars" foreach ($line in $product_list) { # 跳过注释行和空行 if ($line -match '^\s*#' -or [string]::IsNullOrWhiteSpace($line)) { continue } # 匹配目标变量并提取值 if ($line -match 'resource_group_postfix\s*=\s*"([^"]+)"') { $resourceGroupPostfix = $matches[1] Write-Host "resource_group_postfix的值: $resourceGroupPostfix" break # 找到后退出循环,提升效率 } }
内容的提问来源于stack exchange,提问作者Muhammad_Bilal
相关产品推荐
相关产品推荐

