Home > database >  Use a path with unknown folder in PowerShell
Use a path with unknown folder in PowerShell

Time:12-29

Let's say I have this folder tree on Windows:

C:/
├─ random_folder_name1/
│  ├─ file1.txt
├─ random_folder_name2/
│  ├─ file2.txt

I don't know any folder name inside C:\ and I want to acces to file1.txt in a command (ReadAllBytes for example in this case). Is there a way to do this? I would like something like that :

$FilePath = 'C:\*\file1.txt';
$fileBytes = [System.IO.File]::ReadAllBytes($FilePath);

But the code above is not working and obviously says that FilePath with the '*' is not a valid format.

CodePudding user response:

You can search for files and get the path back like this

gci -recurse -filter 'filename' -Path "C:\"

To get back only the path, you can add the following

gci -recurse -filter 'filename' -Path "C:\" | %{$_.FullName}

CodePudding user response:

Well my bad I found the answer just after posting this... (I searched before)

replace $FilePath = 'C:\*\file1.txt'; with $FilePath = Resolve-Path -Path 'C:\*\file1.txt';

  • Related