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

PowerShell中如何将properties哈希表转换回原始字符串格式回写

PowerShell 哈希表转properties格式写入文件方法

基础实现(无序哈希表)

直接遍历哈希表的键值对,拼接为key=value格式后写入文件即可:

# 生成properties格式的行集合
$outputContent = $configuration.GetEnumerator() | ForEach-Object {
    "$($_.Key)=$($_.Value)"
}

# 写入文件,可根据需求调整编码格式
# PowerShell 7+ 写入UTF-8无BOM文件
$outputContent | Set-Content -Path "你的配置文件路径.properties" -Encoding UTF8

# PowerShell 5.1 写入UTF-8无BOM文件
$utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllLines("你的配置文件路径.properties", $outputContent, $utf8NoBomEncoding)

保留原始键顺序的实现

ConvertFrom-StringData默认返回无序哈希表,如果你需要保留原properties文件的键顺序,建议读取时直接生成有序哈希表:

# 读取properties文件为有序哈希表
$configuration = [ordered]@{}
Get-Content -Path "你的配置文件路径.properties" | ForEach-Object {
    # 跳过空行和注释行
    if ([string]::IsNullOrWhiteSpace($_) -or $_.TrimStart().StartsWith('#')) {
        return
    }
    # 按第一个等号分割键值,避免值中包含等号时出错
    $splitIndex = $_.IndexOf('=')
    $key = $_.Substring(0, $splitIndex).Trim()
    $value = $_.Substring($splitIndex + 1).Trim()
    $configuration[$key] = $value
}

用有序哈希表生成的properties文件,键顺序会和原始文件完全一致。

注意事项

  • 如果你需要保留properties文件中的注释、空行,不要使用ConvertFrom-StringData处理原始文件,该方法会自动忽略注释和空行,建议用上面逐行读取的方式自行处理。
  • 键值分割时指定最大分割逻辑,可以兼容值中包含等号的场景。

内容的提问来源于stack exchange,提问作者Sara June

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:57:04