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

PowerShell:ConvertFrom-StringData逆向操作及哈希表存回文件的更优方法

PowerShell: Writing a Hashtable Back to a Key=Value Text File

Great question! Let's start by confirming: your current approach works perfectly, and it's actually the most straightforward general-purpose solution for this scenario.

First, the quick context: PowerShell doesn't have a built-in counterpart to ConvertFrom-StringData specifically for writing hashtables back to key=value formatted text. That said, we can simplify your existing code for cleaner syntax, and handle edge cases if needed.

Simplified Versions of Your Current Approach

Your core logic is solid—enumerating the hashtable's key-value pairs and formatting each line as key=value is exactly what you need. Here are a few more concise ways to write it:

For PowerShell 5.1 and above

Use string interpolation instead of the -f format operator for more readable code:

$values.GetEnumerator() | ForEach-Object { "$($_.Name)=$($_.Value)" } | Set-Content $Path

For PowerShell 7+

Leverage the Join-String cmdlet to cut out the explicit ForEach-Object (this is mostly a syntax shortcut, but cleans up the line):

$values.GetEnumerator() | Join-String -Property { "$($_.Name)=$($_.Value)" } | Set-Content $Path

Handling Special Characters

If your hashtable values contain characters like = or \ (which have special meaning to ConvertFrom-StringData), you'll want to escape them to ensure the file can be read back correctly. Here's how to adjust your code for that:

$values.GetEnumerator() | ForEach-Object {
    # Escape = and \ to match ConvertFrom-StringData's parsing rules
    $escapedValue = $_.Value -replace '([=\\])', '\$1'
    "$($_.Name)=$escapedValue"
} | Set-Content $Path

Why There's No "One-Cmdlet" Solution

The reason there's no direct reverse of ConvertFrom-StringData is that key=value files are a simple, ad-hoc format—unlike structured formats like JSON or XML, which have dedicated ConvertTo-* cmdlets. Your original approach is essentially the de facto standard for this task in PowerShell.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:12:40