Как удалить конкретный элемент в INI-файле с помощью PowerShell? - PullRequest
1 голос
/ 27 марта 2019

Я хочу удалить определенный элемент в моем 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 Ответ

1 голос
/ 27 марта 2019

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

Тогда назовите это следующим образом; обратите внимание на пропуск 4-го аргумента, который требует удаления записи:

.\script.ps1 file.ini Information Age
...