我有一組編號為 1-100 的檔案,其元資料包含以下內容(示例):
檔案名:10.dat
{"name":"Personnel 42589" ,"configuration":...}
我想替換檔案中的數字以匹配檔案名,所以結果應該是:
檔案名:10.dat
{"name":"Personnel 10" ,"configuration":...}
我正在嘗試對所有 100 個檔案執行相同的操作,我的第一個猜測是使用 Notepad ,但它似乎不可行。
uj5u.com熱心網友回復:
您的檔案內容看起來像一個僅包含一個物件的單行 JSON 字串。如果是這樣,您可以使用以下方法:
Get-ChildItem -Filter *.dat | ForEach-Object {
$fromJson = Get-Content -Raw $_.FullName | ConvertFrom-Json
$fromJson.name = $fromJson.name -replace '\d ', $_.BaseName
# Print the results to the *console* for inspection.
[pscustomobject] @{ FileName = $_.Name; NewContent = ConvertTo-Json -Compress $fromJson }
# Once you're happy with the results, activate the following instead.
# CAUTION: This will rewrite the files *in place*.
# Set-Content $_.FullName (ConvertTo-Json -Compress $fromJson)
}
注意重新字符編碼:Set-Content在重寫檔案時使用其默認編碼,這可能與輸入編碼不同 --Encoding根據需要使用引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434574.html
標籤:电源外壳
上一篇:使用PowerShell對多個PowerBI作業區進行掃描儀API呼叫
下一篇:決議物件內部的字串
