循环替换c:\,d:\ ... z:\ with \\ servername \ c $ \

问题描述 投票:-1回答:2

我实际上正在尝试构建一些代码来识别我企业中每个服务器中共享文件夹的权限。

现在,我已经列出了每个服务器并将其导出到.txt文件中,在此.txt上执行了一个循环,以便在其他.txt文件中导出所有共享文件夹。

这一切都很好,但路径就像:c:\...\...\folder$。为了能够使用这个我需要做一个循环用c:\替换d:\ \\servername\c$\等。

我尝试过使用[system.io.file]::ReadAllTextWriteAllText,它在一个字母上运行正常,但没有找到办法对它进行循环。

我试过了

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

但是关于正则表达式无效的错误,所以尝试使用[regex]::Escape但是没有按预期工作...

电源外壳

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

电源外壳

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

我希望有类似的东西:

电源外壳

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

但我在Powershell中太新手了,以使其正常工作

powershell shared-directory access-rights
2个回答
0
投票
  • 你需要PSv6才能使用'a'..'z'
  • -replace运算符是基于RegEx的,你需要在模式中使用另一个转义字面反斜杠。
  • 以下@Lee_Daileys提示使用有效的驱动器号构建一个RegEx

$OFS = '|'
$RE  = ('('+(Get-Psdrive -PSProvider filesystem).where({$_.Displayroot -notmatch '^\\'}).name)+'):\\'
$OFS = $Null

"`$RE = '{0}'" -f $RE

'Loop to replace c:\, d:\ … z:\ with \\servername\c$\' -replace $RE,"\\servername\`${1}$\"

我的电脑上的示例输出

$RE = '(A|C|D):\\'
Loop to replace \\servername\c$\, \\servername\d$\ … z:\ with \\servername\c$\

使用-raw参数读取文件不需要循环,但会立即执行所有更改。

$OFS = '|'
$RE  = ('('+(Get-Psdrive -PSProvider filesystem).where({$_.Displayroot -notmatch '^\\'}).name)+'):\\'
$OFS = $Null

$File = "$path\$SharedFolders.txt"
(Get-Content $File -raw) -replace $RE,"\\servername\`${1}$\" |
 Set-Content $File

0
投票

谢谢你的帮助,我只是设法让它像那样工作:


$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++
}

希望它能帮助一些人;)

© www.soinside.com 2019 - 2024. All rights reserved.