powershell - 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
}
}
这在替换行上是错误的。
解决方案
这用于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
推荐阅读
- android - 当我尝试从 Android 中的 AWS Dyanamodb 读取数据时出现 NullPointer 异常错误?
- c - 带有一个输入的 strcmp 的分段错误
- python - 构造函数重载python
- python - 使用 Python 和 Selenium,我将如何绕过 2 因素身份验证?
- r - 在 macOS Catalina 上为 Jupyter 提供内核时出现 IRkernel::installspec() 错误
- javascript - 最后一个选项卡下一个按钮将其重定向到主页
- game-physics - Godot - 从脚本中获取物理 fps?
- python - Python:为 Pandas Dataframe 中的列表计算 PMF
- caching - 设置关联缓存 - 有多少内存块映射到一组?
- ubuntu - Ubuntu - 使用用户输入的顺序文件命名