如何使用powershell将csv中的sid更改为用户?

时间:2012-08-30 15:17:15

标签: powershell csv

这似乎是基本但无法找到或弄清楚任何地方。

我有一个我要导入的.csv文件,将具有不同SID的用户列更改为对应的用户名,然后导出回.csv。我知道如何找到SIDtoUser,但我无法弄清楚如何在.csv中进行替换。此外,一些用户列是空白的或具有“admin”,我需要单独留下。

当前

ComputerName,   TimeStamp,  Message,    User               
hp8440,         8/30/2012,  message1,   admin  
hp8440,         8/30/2012,  message2  
hp8440,         8/30/2012,  message3,   S-1-5-21...1105  
hp8440,         8/30/2012,  message4,   S-1-5-21...1255

想要阅读

ComputerName,   TimeStamp,  Message,    User  
hp8440,         8/30/2012,  message1,   admin  
hp8440,         8/30/2012,  message2  
hp8440,         8/30/2012,  message3,   user1  
hp8440,         8/30/2012,  message4,   user2

2 个答案:

答案 0 :(得分:1)

Import-Csv .\sid.csv | ForEach-Object{

    if($_.User -and $_.User -ne 'admin')
    {
        # User is not empty and not admin
        # perform translation and assign the results back to the User column
        # then return the current object back to the pipeline
        $_.User = (New-Object System.Security.Principal.SecurityIdentifier $_.User).Translate([System.Security.Principal.NTAccount]).Value
        $_
    }
    else
    {
        # Ignore empty User or admin 
        # and return the current object back to the pipeline
        $_
    }

} | Export-Csv .\users.csv

答案 1 :(得分:0)

作为一个单行:

Import-Csv .\data.csv |%{ $_.User = ConvertSidToUserName $_.User; $_ } | Export-Csv .\updated.csv

更具可读性......

$data = Import-Csv .\data.csv

# replace the User Propery
$data |%{ $_.User = ConvertSidToUserName $_.User }

# export back out to csv
$data | Export-Csv .\updated.csv