Powershell INI 编辑 [英] Powershell INI editing

查看:46
本文介绍了Powershell INI 编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改 INI 文件中的一些值.不幸的是,我在 2 个不同的部分有键,它们共享相同的名称但需要不同的值.我的代码使用 PsIniGet-IniContent 函数>.

I want to changing some values in an INI file. Unfortunately, I have keys in 2 different sections which share an identical name but need different values. My code uses the Get-IniContent function from PsIni.

示例 INI 文件:

[PosScreen]
BitmapFile=C:\Temp\Random.bmp
Bitmap=1

[ControlScreen]
BitmapFile=C:\Temp\Random.bmp
Bitmap=1 

我需要将以上内容更改为以下内容:

I need to change the above to the following:

[PosScreen]
BitmapFile=C:\Temp\FileC.bmp
Bitmap=1

[ControlScreen]
BitmapFile=C:\Temp\FileD.bmp
Bitmap=1 

我使用的 PowerShell 代码似乎可以工作,但它将每个值都更改为文件 D".很明显是把所有东西都解析了两次,而且每个部分的名字都一样.

The PowerShell code I am using seems to work, but it changes every value to "File D". It is obviously parsing everything twice, and the name is the same for each section.

$NewFileC = "C:\Temp\FileC.bmp"
$NewFileD = "C:\Temp\FileD.bmp"
$POSIniContent = Get-IniContent "C:\scripts\Update-EnablerImage\WINSUITE.INI"
$BOIniContent = Get-IniContent "C:\scripts\Update-EnablerImage\WINSUITE.INI"

If ($POSIniContent["PosScreen"]["BitmapFile"] -ne $NewFileC) {
  Get-Content "C:\scripts\Update-EnablerImage\WINSUITE.INI" |
    ForEach-Object {$_ -replace "BitmapFile=.+" , "BitmapFile=$NewFileC" } |
    Set-Content "C:\scripts\Update-EnablerImage\WINSUITE.INI"
}

If ($BOIniContent["ControlScreen"]["BitmapFile"] -ne $NewFileD) {
  Get-Content "C:\scripts\Update-EnablerImage\WINSUITE.INI" |
    ForEach-Object {$_ -replace "BitmapFile=.+" , "BitmapFile=$NewFileD" } |
    Set-Content "C:\scripts\Update-EnablerImage\WINSUITE.INI"
}

我的挣扎是如何独立地改变每一个.我是一个脚本新手,所以需要一些帮助.尝试使用条件逻辑(例如,ForEach $line in $INIFile),但没有成功.

My struggle is how to change each one independently. I'm a bit of a scripting newbie, so calling out for some help. Tried using Conditional Logic (ForEach $line in $INIFile, for example), but no luck with that.

推荐答案

你把事情复杂化了.您可以使用 Get-IniContentOut-IniFile 如下:

You are overcomplicating things. You can use Get-IniContent and Out-IniFile as follows:

$ini = Get-IniContent c:\temp\ini.ini 
$ini["posscreen"]["BitmapFile"] = "C:\Temp\FileC.bmp"  
$ini | Out-IniFile -FilePath c:\temp\ini2.ini

注意,如果要覆盖原文件,必须在Out-IniFile调用中添加-Force.

Note that if you want to overwrite the original file, you must add -Force to the Out-IniFile call.

这篇关于Powershell INI 编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆