Search code examples
powershellshared-directoryaccess-rights

Loop to replace c:\, d:\ ... z:\ with \\servername\c$\


I'm actually trying to build some code to identify rights on shared folders in every single server I've got in my enterprise.

For now, I've already listed every single server and exported it in a .txt file, did a loop on this .txt to export in an other .txt file all shared folders.

All this is working fine but the path is like : c:\...\...\folder$. To be able to use this I need to do a loop to replace c:\ d:\ etc. with \\servername\c$\.

I've tried using [system.io.file]::ReadAllText and WriteAllText, it's working fine for one letter but didn't find a way to do a loop on it.

I've tried

get-content ... -replace "c:\","\\$ServerName\c$\" ` -replace "d:\" ... 

but got an error about regular expression not valid, so trying with [regex]::Escape but didn't work as expected neither...

Powershell

$contenu = [System.IO.File]::ReadAllText("$path\$SharedFolders.txt").Replace("C:\","\\$SharedFolders\c$\")
[System.IO.File]::WriteAllText("$path\$SharedFolders.txt", $contenu)

Powershell

(Get-Content "$path\$SharedFolders.txt") | foreach {
    $_ -replace "C:\","\\$SharedFolders\C$\" `
 -replace "D:\","\\$SharedFolders\D$\" `
[...] | Set-Content "$path\$sharedfolders.txt"}

And i'd like to have something like that :

Powershell

('a'..'z').ForEach({ (Get-Content "$path\$SharedFolders.txt" -Raw).replace("$_`:\","\\$SharedFolders\$_$") })

But I'm too newbie in Powershell to make it work proprely


Solution

  • Well thanks for your help, I just manage to make it works like that :

    
    $lecteur=[int][char]'A'
    
    1..26 | % {
        $LR=[char]$lecteur
        $contenu =[System.IO.File]::ReadAllText("$path\$SharedFolders.txt").Replace("${LR}:\","\\$SharedFolders\$LR$\")
        [System.IO.File]::WriteAllText("$path\$SharedFolders.txt", $contenu)
        $lecteur++
    }
    

    Hope it'll help some people ;)