string - 拆分路径并仅取出最后一部分(文件名)Powershell
问题描述
我对powershell非常陌生,我目前正在尝试编写一个脚本,该脚本在文件中找到引用的文件路径,只取出路径的最后一部分(文件名)并将其移动到与包含它的文件夹相同的目的地。
我有一个功能脚本可以做我想要的,唯一剩下的是它不应该查找引用文件的整个路径。因为路径不再正确。它应该只查找文件名并找到并移动它。
这是我当前的脚本:
$source = 'Z:\Documents\16_Med._App\Aufträge\RuheEKG_24HBP_Skript\Ursprung_test'
$destination = 'Z:\Documents\16_Med._App\Aufträge\RuheEKG_24HBP_Skript\24BHD'
$toDelete = 'Z:\Documents\16_Med._App\Aufträge\RuheEKG_24HBP_Skript\ToDelete'
$pattern1 = 'AmbulatoryBloodPressure'
$pattern2 = 'RuheEKG'
# Erstellt Array mit pfad und filename
$allFiles = @(Get-ChildItem $source -File | Select-Object -ExpandProperty FullName)
foreach($file in $allFiles) {
# Dateinhalt als Array
$content = Get-Content -Path $file
# Wählt Destinationspfad
if ($content | Select-String -Pattern $pattern1 -SimpleMatch -Quiet)
{
$dest = $destination
}
else {
$dest = $toDelete
}
# Prüft ob Datei einen Pfad enthält
$refCount = 0
$content | Select-String -Pattern '(^.*)([A-Z]:\\.+$)' -AllMatches | ForEach-Object {
$prefix = $_.Matches[0].Groups[1].Value
$refPath = $_.Matches[0].Groups[2].Value # Bitmap file Path wird geholt
if (Test-Path -Path $refPath -PathType Leaf) {
Write-Host "Moving referenced file '$refPath' to '$dest'"
Move-Item -Path $refPath -Destination $dest -Force
}
else {
Write-Warning "Referenced file '$refPath' not found"
}
}
$refPath -split "\"
$refPath[4]
write-host $refpath
# Bewegt die Files an die vorher festgelegte Destination.
Write-Host "Moving file '$file' to '$dest'"
Move-Item -Path $file -Destination $dest -Force
}
解决方案
您有几个选项可以在 PowerShell 中轻松使用文件路径和名称。
内置 cmdlet
# Get the file name
$fileName = Split-Path $refPath -Leaf
# Get the directory path
$dirPath = Split-Path $refPath -Parent
.NET 方法
# Get the file name
$fileName = [System.IO.Path]::GetFileName($refPath)
# Get the directory path
$dirPath = [System.IO.Path]::GetDirectoryName($refPath)
如果要在另一个目录中查找文件名,可以像这样构建一个新路径:
# built-in version
$otherPath = Join-Path $otherDir $fileName
# .NET version
$otherPath = [System.IO.Path]::Combine($otherDir, $fileName)
推荐阅读
- angular - Angular 7 build--prod 生成的文件
- angular - 如何在 Angular 7 中获得正确的生命周期钩子
- javascript - 迭代具有相互引用的对象数组并将这些从字符串解析为对象
- xml - XCAP xml 格式
- qr-code - Zebra ZPL II 代码可缩放 QR 代码 (^BQ)
- java - 使用 lombok 时设置 log4j 级别
- bash - 使用 bash 脚本创建 gzip 文件
- oracle - 为什么在我的 AutoField 模型中指定主键时必须明确指定主键?
- python - 双计数循环(n*n 代码性能)
- python - 将多个以字符串开头的csv文件读入python中的单独数据帧