我目前正在写一个自动化的脚本。该脚本应该有一个全局计数变量,该变量在再次执行该脚本时不会自行重置。因此,我需要一个配置文件来存储这个count变量,并在再次调用它时使用它。此计数变量也依赖于ID。因此,每个ID都有一个计数变量。配置文件可以是XML或INI格式。谁能告诉我如何以最简单的方式创建这样的文件,以及如何添加ID或获取计数变量?我不认为"csv-import/export“是正确的方式。
我已经试过了..。
$results = @()
$details = @{
Key1 = $ID
Key2 = $count
Key3 = "sth"
Key4 = "sth"
Key5 = "sth"
}
$results += New-Object PSObject -Property $details
$results | export-csv -Path C:\Users\...\configure.txt -NoTypeInformation不幸的是,我不能在这里得到更多信息,因为每次ID更改时它都会覆盖以前的条目,并且我不知道如何添加其他条目(如果ID已经存在)、更新条目(count变量)以及调用此count变量在Powershell中使用它。
有谁有建议吗?
诚挚的问候
发布于 2017-11-30 00:00:26
您可以使用hash table、Export-CliXml和Import-CliXml将您的ID计数保存并加载到XML文件中:
$xmlFilePath = 'idCounts.xml'
# If the XML file exists, it is loaded
if( Test-Path -Path $xmlFilePath -PathType Leaf )
{
$hashTable = Import-Clixml -Path $xmlFilePath
}
# Else a new hash table is initialized
else
{
$hashTable = @{}
}
# Set the count of ID '001' to 1
$hashTable['001'] = 1
# Increment the count of ID '002'
$hashTable['002'] += 1
# Save the hash table to the XML file
$hashTable | Export-Clixml -Path $xmlFilePath发布于 2017-12-01 18:12:31
谢谢你给我的提示。最后,我自己用以下方式管理它:
if(!((import-csv "C:\Users\...\Desktop\ini.txt") | where-object {$_.Key1 -eq $ID}))
{
$results = @()
$details = @{
Key 1 = $ID
Key 2 = 1
Key 3 = "something"
Key 4 = "something"
Key 5 = "something"
Key 6 = "something"
}
$results += New-Object PSObject -Property $details
$results | export-csv -Path C:\Users\...\Desktop\ini.txt -append -NoTypeInformation
}系统首先检查是否存在对应ID的条目,如果没有,则创建一个具有该ID的对象,新建时将count变量设置为1。该条目被附加到带有"Export CSV“的文件中。
$select = (import-csv "C:\Users\...\Desktop\ini.txt" | where{$_.Key1 -eq $ID})
[int]$global:number = [convert]::ToInt32($select.Key2)要使用count变量,需要导入配置文件。我将其设置为"global“,因为它必须在多个函数上运行。
($csv = Import-Csv "C:\Users\...\Desktop\ini.txt") | ForEach {
if ($_.Key1 -eq $ID) {
$_.Key2 = $global:number}
}
$csv | Export-Csv "C:\Users\...\Desktop\ini.txt" -NoTypeInformation 最后,使用"Export CSV“更新计数变量并将其传输回文件。
不过,还是要感谢您提出的所有有趣的建议!
诚挚的问候
https://stackoverflow.com/questions/47553858
复制相似问题