如何使用 PowerShell 删除 INI 文件中的特定项目?
How to remove specific item in INI file using PowerShell?
我想删除 INI 文件中的特定项目。
我的 INI 文件
[Information]
Name= Joyce
Class=Elementry
Age=10
我想删除Age=10
我试过这段代码,但我只能删除 Age
的值,即 10
。
Param(
[parameter(mandatory=$true)]$FilePath,
[parameter(mandatory=$true)] $a,
[parameter(mandatory=$true)] $b,
[parameter(mandatory=$true)] $c
)
Import-Module PsIni
$ff = Get-IniContent $FilePath
$ff["$a"]["$b"] = "$c"
$ff | Out-IniFile -FilePath $FilePath -Force
我对 INI 文件的期望输出是:
[Information]
Name=Joyce
Class=Elementry
Get-IniContent
returns 表示 INI 文件结构的(嵌套)有序哈希表。
因此,要删除条目,您必须使用有序哈希表的 .Remove()
方法:
# Read the INI file into a (nested) ordered hashtable.
$iniContent = Get-IniContent file.ini
# Remove the [Information] section's 'Age' entry.
$iniContent.Information.Remove('Age')
# Save the updated INI representation back to disk.
$iniContent | Out-File -Force file.ini
因此您可以按如下方式修改脚本:
Param(
[parameter(mandatory=$true)] $FilePath,
[parameter(mandatory=$true)] $Section,
[parameter(mandatory=$true)] $EntryKey,
$EntryValue # optional: if omitted, remove the entry
)
Import-Module PsIni
$ff = Get-IniContent $FilePath
if ($PSBoundParameters.ContainsKey('EntryValue')) {
$ff.$Section.$EntryKey = $EntryValue
} else {
$ff.$Section.Remove($EntryKey)
}
$ff | Out-IniFile -FilePath $FilePath -Force
然后调用如下;注意省略了第四个参数,它要求删除条目:
.\script.ps1 file.ini Information Age
我想删除 INI 文件中的特定项目。 我的 INI 文件
[Information]
Name= Joyce
Class=Elementry
Age=10
我想删除Age=10
我试过这段代码,但我只能删除 Age
的值,即 10
。
Param(
[parameter(mandatory=$true)]$FilePath,
[parameter(mandatory=$true)] $a,
[parameter(mandatory=$true)] $b,
[parameter(mandatory=$true)] $c
)
Import-Module PsIni
$ff = Get-IniContent $FilePath
$ff["$a"]["$b"] = "$c"
$ff | Out-IniFile -FilePath $FilePath -Force
我对 INI 文件的期望输出是:
[Information]
Name=Joyce
Class=Elementry
Get-IniContent
returns 表示 INI 文件结构的(嵌套)有序哈希表。
因此,要删除条目,您必须使用有序哈希表的 .Remove()
方法:
# Read the INI file into a (nested) ordered hashtable.
$iniContent = Get-IniContent file.ini
# Remove the [Information] section's 'Age' entry.
$iniContent.Information.Remove('Age')
# Save the updated INI representation back to disk.
$iniContent | Out-File -Force file.ini
因此您可以按如下方式修改脚本:
Param(
[parameter(mandatory=$true)] $FilePath,
[parameter(mandatory=$true)] $Section,
[parameter(mandatory=$true)] $EntryKey,
$EntryValue # optional: if omitted, remove the entry
)
Import-Module PsIni
$ff = Get-IniContent $FilePath
if ($PSBoundParameters.ContainsKey('EntryValue')) {
$ff.$Section.$EntryKey = $EntryValue
} else {
$ff.$Section.Remove($EntryKey)
}
$ff | Out-IniFile -FilePath $FilePath -Force
然后调用如下;注意省略了第四个参数,它要求删除条目:
.\script.ps1 file.ini Information Age