I'm very new to powershell and im currently trying to write a script that finds a referenced filepath in a file, takes out only the last part of the path (The filename) and moves it to the same destination like the folder containing it.
I have a functional script that does what i want, the only thing left is that its not supposed to look for the whole path of the referenced file. Because the path isnt correct anymore. It should just look for the filename and find and move it.
This is my current script:
$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
}