Powershell replace sid in csv with username

54 views Asked by At

I have a csv or txt with workstation names and some sids from registry. I want to replace the sids with user names in the original csv. The sids have a ":" at the end and a letter after that, that's why I use split. I tried also "text but is not working for me. TIA

$sids = Import-csv "C:\temp\sids2.csv" 
foreach($sid in $sids){
if ($sid.'ColumnName' -like "*S-1-5*"){
$ssid = $sid.'ColumnName'.split(":")[0]
$name = ((New-Object System.Security.Principal.SecurityIdentifier ($ssid)).Translate( [System.Security.Principal.NTAccount])).Value
$ssid.Replace("$ssid","$name")}
}

It doesn't change the csv file.

Same for:

Import-Csv "C:\temp\sids2.csv" | ForEach-Object{

    if($_.sid -and $_.sid -like "*S-1-5*")
    {
        # 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
        $_.sid = (New-Object System.Security.Principal.SecurityIdentifier $_.sid).Translate([System.Security.Principal.NTAccount]).Value
        $_
    }
    else
    {
        # Ignore empty User or admin 
        # and return the current object back to the pipeline
        $_
    }

} | Export-Csv c:\temp\users.csv

The new csv is same as source csv.

csv example:

ws,date,time,sid,sid1,sid2,sid3,sid4  
WSxxx,13/03/2024,14:36:00,S-1-5-**-*******-*******-****:d,admin:f,,,  
WSzzz,13/03/2024,14:48:00,admin:f,%S-1-5-**-*******-*******-****:d,%S-1-5-**-***:d,,,
1

There are 1 answers

0
Dimitris Magkriotis On

Solution:

$all = Import-csv "c:\temp\sid.csv"

 foreach($a in $all){
 if ($a.sid -and $a.sid -like "*S-1-5*"){
 $aa = $a.sid.split(":")[0]
 $a.sid = (New-Object System.Security.Principal.SecurityIdentifier ($aa)).Translate([System.Security.Principal.NTAccount]).Value
 }
 $all | export-csv "c:\temp\sid.csv" -NoTypeInformation -Force
 }