拆分路径并仅提取最后一部分(文件名)PowerShell

4
我很新手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
}

这是参考位图文件: 输入图片描述

你的正则表达式似乎不正确(^. *)将匹配以任意字符为开头的任何行... 顺便说一句,我宁愿不要在这么早的时候将$allFiles的路径转换为字符串。如果你保留路径作为路径对象,你可以更轻松地后续使用其成员,如.FullName.DirectoryName - T-Me
作为路径的正则表达式,[A-Za-z]:(\\[\w\s-]*)+(\.\w{3}) 怎么样?你不需要关心行开头的数字。 - T-Me
这个回答解决了你的问题吗?从路径中提取文件名 - cachius
2个回答

8
你有几个选项可以在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)

4
要获取要移动的文件的文件名,请使用marsze建议的Split-Path
$FileName = Split-Path $refPath -Leaf

要定位文件,请使用Get-ChildItem。($SearchBase是您要搜索的路径)

$FileLocation = (Get-ChildItem -Path $SearchBase -Filter $filename -Recurse -File).FullName

现在,要移动文件,请使用Move-Item命令,并再次使用Split-Path命令查找目标位置。
Move-Item -Path $FileLocation -Destination $(Split-Path $file -Parent)

他正在搜索一个文本文件的文件路径。路径已经改变,但是文件仍然存在。因此,他想将该文件移动到文本文件的位置。所以,我认为该文本文件的位置是存在的。 - T-Me

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接