使用PowerShell将唯一ID添加到CSV

lhcgjxsq  于 2023-09-27  发布在  Shell
关注(0)|答案(2)|浏览(83)

我有一个CSV与服务器名称在1列和软件上运行的服务器在另一个。由于服务器重复多次(* 由于与之关联的不同软件)*,我不能只为我的ID做count++,所以基本上,在自动分配ID时,只有当服务器名称更改时,ID才必须更改,我如何才能完成这一任务?
期望输出

╔════╦═════════╦═══════════╗
║ ID ║ Server  ║ Software  ║
╠════╬═════════╬═══════════╣
║  1 ║ Server1 ║ Software1 ║
║  1 ║ Server1 ║ Software2 ║
║  2 ║ Server2 ║ Software1 ║
║  3 ║ Server3 ║ Software1 ║
║  3 ║ Server3 ║ Software2 ║
╚════╩═════════╩═══════════╝
unftdfkk

unftdfkk1#

你可以使用Group-Object来实现,如下所示:

$data = Import-Csv -Path 'D:\Test\input.csv'  # enter the path to your input csv file here
$id   = 1  # initial server ID

$result = $data | Group-Object -Property Server | ForEach-Object {
    # get the current id value and increment $id for the next server group
    $svrId = $id++
    foreach ($item in $_.Group) {
        # output an object with ID property included
        [PsCustomObject]@{
            ID = $svrId
            Server = $item.Server
            Software = $item.Software
        }
    }
}

# output on screen
$result

# save as CSV file
$result | Export-Csv -Path 'D:\Test\output.csv' -NoTypeInformation
w9apscun

w9apscun2#

另一个解决方案:

#Generate the array for the example
$ServerArray = @()
$ServerArray += [PsCustomObject][Ordered]@{Server = "Server1";Software = "Software1"}
$ServerArray += [PsCustomObject][Ordered]@{Server = "Server1";Software = "Software2"}
$ServerArray += [PsCustomObject][Ordered]@{Server = "Server2";Software = "Software1"}
$ServerArray += [PsCustomObject][Ordered]@{Server = "Server3";Software = "Software1"}
$ServerArray += [PsCustomObject][Ordered]@{Server = "Server3";Software = "Software2"}

#Property to be used for incrementing the Id
$Property = "Server"
#Intiate the Id and the Value, Global variable are required for being able to keep the value of the previous iteration
$Global:Id=0
$Global:Value=$null

#Define the expression to be used for the additional Id Property
$ExpId = @{E={if($Global:Value -ne $_."$($Property)"){$Global:Value=$_."$($Property)";$Global:Id++};$Global:Id};L="Id"}

#Add an Id property for each item
$ServerArray = $ServerArray | Sort-Object Server | select $ExpId,*

#Display Result
$ServerArray | ft *

#Export result with Id in csv file
$CsvFilePath = Join-Path $Env:TEMP "tempfile.csv"
$ServerArray | Export-Csv -Path $CsvFilePath -NoTypeInformation

相关问题