I'm looking to optimize this script with a function
$Folder = 'K:\dxf\dxf50000-60000'
$filenames = Get-Content -Path .\files.txt
$missingFilesList = New-object System.Collections.ArrayList
Write-Host "Folder: $folder."
Write-Host "Searching for files"
foreach ($filename in $filenames) {
$found=$false;
Get-ChildItem -Path $Folder -Recurse | ForEach-Object {if($filename -eq $_.BaseName) {Write-Host 'FILE ' $filename ' Ok' -foregroundcolor green; $found=$true;CONTINUE }$found=$false;} -END {if($found -ne $true){ Write-Host 'FILE ' $filename ' missing in the folder' -foregroundcolor red}}
}
Generally I'm looking for files with the same format everytime: basename-revision
51713-0 51762-0 51780-0
Now I also want to search for the basename (i.e 51713) and report this back with the basename and revision if found (and change the color to cyan or something) - what would be the best way to achieve this?
This should work
My C:\files.txt contains the following content:
51713-0 51714-0 51714-1 51714-2 51714-3 51799-0
# Define the folder where we look for the files
$FilesFolder = 'C:\dxf50000-60000'
# Define the list of files to check for
$FileNameList = Get-Content -Path c:\files.txt
# Get all the files in the FilesFolder
$ContainingFiles = Get-ChildItem $FilesFolder
Write-Host "Folder: $FilesFolder."
Write-Host "Searching for files"
# Go through each file in the FilesFodler
foreach ($FileName in $FileNameList) {
# Define basename
$BaseName = $FileName.Split("-")[0]
# Define revision
$Revision = $FileName.Split("-")[1]
# If the folder contains a matching basename AND revision, write output GREEN
If ($ContainingFiles.Name -like "*$BaseName-$Revision*"){
Write-Host "Successfully found file basename [$BaseName] with revision [$Revision]" -ForegroundColor Green
# If the folder contains a matching basename but NOT revision, write output CYAN
}ElseIf ($ContainingFiles.Name -like "*$BaseName*"){
Write-Host "Successfully found file basename [$BaseName] with revision [$Revision]" -ForegroundColor Cyan
# If no matching basename was found, write output RED
}Else{
Write-Host "Failed to find file with basename [$BaseName]" -ForegroundColor Red
}
}