首页 > 解决方案 > Powershell 脚本 - 为文本文件中给出的所有 URI 替换 FilePath

问题描述

我是 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
    }
}

这在替换行上是错误的。

标签: powershell

解决方案


这用于Split-Path获取文件名。然后它用于Join-Path构建新的完整路径。[咧嘴笑]

$SourceFile = "$env:TEMP\Reddy-In.txt"
$DestFile = "$env:TEMP\Reddy-Out.txt"

# create a file to work with
#    remove this section when ready to use your own data
@'
C:\Project\SharedLib\Shared\log4net.dll
C:\Project\SharedLib\Shared\Aspose.dll
C:\Dependency\SL\UnStable\Crystal.dll
'@ | Set-Content -LiteralPath $SourceFile

$Prefix = '\\ServerName\websites$\Stable\Release'

$InStuff = Get-Content -LiteralPath $SourceFile
$Results = foreach ($IS_Item in $InStuff)
    {
    $FileName = Split-Path -Path $IS_Item -Leaf
    Join-Path -Path $Prefix -ChildPath $FileName
    }

# display on screen
$Results

# send to a text file
$Results |
    Set-Content -LiteralPath $DestFile

画面输出...

\\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

推荐阅读