You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中读取Here-string模板用于字符串处理?

问题1:将here_string.txt内容读取到$hereString变量中

要从文件中还原here-string内容,只需读取文件后移除@'和'@标记即可:

# 读取文件为单行字符串(保留换行符)
$fileContent = Get-Content -Path .\here_string.txt -Raw

# 提取@'和'@之间的核心内容
$hereString = $fileContent -replace '^@''\r?\n([\s\S]*?)\r?\n''@$', '$1'

# 验证结果
$hereString

执行后$hereString会输出原始的键值对内容:

foo : {abc}
bar : {123}
baz : {a1b2c3}

问题2:读取recordTemplate.txt并解析records.txt

步骤1:提取纯模板内容

recordTemplate.txt包含变量赋值和here-string标记,先剥离无关部分得到纯模板:

# 读取模板文件内容
$templateRaw = Get-Content -Path .\recordTemplate.txt -Raw

# 移除变量赋值和here-string标记,提取核心模板
$recordTemplate = $templateRaw -replace '^\$recordTemplate = @''\r?\n([\s\S]*?)\r?\n''@$', '$1'

步骤2:用模板解析记录文件

通过ConvertFrom-String结合提取的模板,将records.txt的文本转换为结构化对象:

# 读取待解析的记录文件
$recordsRaw = Get-Content -Path .\records.txt -Raw

# 解析为自定义对象数组
$parsedRecords = $recordsRaw | ConvertFrom-String -TemplateContent $recordTemplate

# 查看解析结果
$parsedRecords

解析后的$parsedRecords是包含两个对象的数组,每个对象对应一条用户记录,自动映射UserPrincipalName、DisplayName等属性。


内容的提问来源于stack exchange,提问作者Nicholas Saunders

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:15:33