我是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
}
}
这在替换行上出错。请帮忙!
答案 0 :(得分:0)
这使用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
答案 1 :(得分:0)
我收到的错误消息是
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 pattern-,我们需要对运算符进行转义。 (这就是为什么您经常会看到反斜杠加倍的原因-它们被转义了。)
无需记住它们的全部-您可以使用[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
}
}