如何使用PowerShell删除INI文件中的特定项目?

时间:2019-03-27 05:24:41

标签: powershell ini

我想删除我的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

1 个答案:

答案 0 :(得分:1)

Get-IniContent返回一个(嵌套的)有序哈希表,该表代表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
相关问题