Powershell脚本-替换文本文件中给定的所有URI的文件路径

Powershell脚本-替换文本文件中给定的所有URI的文件路径,powershell,Powershell,我对Power Shell不熟悉 给定一个文本文件,其中有多个文件路径,每个路径之间用新行分隔,我试图用同一文件的新路径替换其中每个路径的文件路径 例如: 输入文件: C:\Project\SharedLib\Shared\log4net.dll C:\Project\SharedLib\Shared\Aspose.dll C:\Dependency\SL\UnStable\Crystal.dll 输出文件: \\ServerName\websites$\Stable\Release\log4

我对Power Shell不熟悉

给定一个文本文件,其中有多个文件路径,每个路径之间用新行分隔,我试图用同一文件的新路径替换其中每个路径的文件路径

例如: 输入文件:

C:\Project\SharedLib\Shared\log4net.dll
C:\Project\SharedLib\Shared\Aspose.dll
C:\Dependency\SL\UnStable\Crystal.dll
输出文件:

\\ServerName\websites$\Stable\Release\log4net.dll
\\ServerName\websites$\Stable\Release\Aspone.dll
\\ServerName\websites$\Stable\Release\Crystal.dll
我的尝试:

Get-ChildItem "*.txt" -Filter *.txt | 
Foreach-Object {

    foreach($line in Get-Content $_) {

        $currentPath = [System.IO.Path]::GetDirectoryName($line)
        ($line) -replace $currentPath, '\\ServerName\websites$\Stable\Release\' | Set-Content $line
    }
}

替换行出错。

这使用
分割路径
获取文件名。然后使用
连接路径
构建新的完整路径。[咧嘴笑]

屏幕输出

\\ServerName\websites$\Stable\Release\log4net.dll
\\ServerName\websites$\Stable\Release\Aspose.dll
\\ServerName\websites$\Stable\Release\Crystal.dll
文本文件内容

\\ServerName\websites$\Stable\Release\log4net.dll
\\ServerName\websites$\Stable\Release\Aspose.dll
\\ServerName\websites$\Stable\Release\Crystal.dll

我收到的错误消息是

The regular expression pattern C:\Project\SharedLib\Shared is not valid.
At C:\temp\StackOverflow.ps1:6 char:9
+         ($line) -replace $currentPath, '\\ServerName\websites$\Stable ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (C:\Project\SharedLib\Shared:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression
这告诉我字符串C:\Project\SharedLib被视为-并且我们需要转义操作符。(这就是为什么你经常会看到反斜杠折叠起来——它们是逃逸的。)

不需要记住它们都是什么-您可以使用[regex]::escape($currentPath)来为您完成

Get-ChildItem "*.txt" -Filter *.txt | 
Foreach-Object {

    foreach($line in Get-Content $_) {

        $currentPath = [System.IO.Path]::GetDirectoryName($line)
        ($line) -replace [regex]::escape($currentPath), '\\ServerName\websites$\Stable\Release\' | Set-Content $line
    }
}
Get-ChildItem "*.txt" -Filter *.txt | 
Foreach-Object {

    foreach($line in Get-Content $_) {

        $currentPath = [System.IO.Path]::GetDirectoryName($line)
        ($line) -replace [regex]::escape($currentPath), '\\ServerName\websites$\Stable\Release\' | Set-Content $line
    }
}