Home > database >  PowerShell: Is there a way to search an specific word in a file's name and open the file if it
PowerShell: Is there a way to search an specific word in a file's name and open the file if it

Time:12-07

I haven't been able to figure out how to make this task that sounds simple in PowerShell.

I am trying to make a powershell variable that represents a file only using a part of it's name, since the rest of the name changes periodically. This should represent a little better what is my intention.

#Each day the number changes except for the Name part.
 Name1, Name2, Name3...

#Variable must be able to work regardless of the number it has since the Name part never changes.
 $Variable: Volume\Folder\Name(X).exe

I'm sorry if i'm not explaining myself well enough. I'll provide any aditional information that is needed.

CodePudding user response:

Run script where you want to search.

$all_files = ls $filename = Read-Host "Enter File Name" foreach ($item in $filename) { if ($item -match $filename) { Get-Content $item } }

CodePudding user response:

Well, to me it seems to be two diiferent tasks at hand:

First your title suggests You are lokking for a way to check the filenames of files in a given directory i assume and run that file with the default filehandler (again i can only speculate)

# 1. task
$path="C:\myfolder\" 
$mySearchKey="taxes"
$myItmes=Get-ChildItem -Path $myPath  
foreach($item in $myItems){ 
   if($item.name -like "*$mySearchkey*"){
      $matchingPath=$path $item.name
      Invoke-Item $matchingPath
   }
}

Secondly In your description and the code example the question seems to be evolving around the idea to create dynamic variables for filenames most likely for the files we where opening before, based on the day in relation to a start date:

 #2. task    
    $afileName="Marry"
    $startdate= Get-Date "2022-12-06"
    $todays= get-date
    $numberOfDays = New-TimeSpan -Start $startdate -End $todays
    $numberOfDays   # since a differnce of 0 days means your in the 1. day
    $newPath="Volume\Folder\" $afileName $numberOfDays ".exe"

But I yet have to figure out your end-game. How are the two coming together?

  • Related