2

I'm trying to write a script in PowerShell which reads in a "foreach" loop all the only files in a specific folder which contains "example" in it's name. The problem is that I'm trying to save the content of each file in a variable without any success. Tried to use Get-Content $file and it throws the following error "Get-Content : Cannot find path" even though the path was set at the beginning to the Folder var and file actually contains the file that I need. I can't assign it to $FileContent

$Folder = Get-ChildItem U:\...\Source

foreach($file in $Folder)
{
    if($file.Name -Match "example")
    {
        $FileContent = Get-Content $file                
    }
}
Marked One
  • 59
  • 4
  • 13

3 Answers3

8

This happens as the FileInfo object's default behavior returns just the file's name. That is, there is no path information, so Get-Content tries to access the file from current directory.

Use FileInfo's FullName property to use absolute path. Like so,

foreach($file in $Folder)
{
...
    $FileContent = Get-Content $file.FullName
vonPryz
  • 22,996
  • 7
  • 54
  • 65
  • Great fix, upvoted. PowerShell's error message is ridiculous though. It says that it cannot find the path because it does not exist and then displays the full (valid) path obtained from `Get-ChildItem` in the error message. – Lews Therin Sep 11 '18 at 17:40
1

Change your working directory to U:\...\Source and then it shall work.

Use

cd U:\...\Source
$folder = gci U:\...\Source

After you are done with your work, you can change your working directory again using cd command or the push-location cmdlet.

Vivek Kumar Singh
  • 3,223
  • 1
  • 14
  • 27
0

try this:

Get-ChildItem U:\...\Source -file -filter "*example*" | %{

$FileContent = Get-Content $_.fullname

}
Esperento57
  • 16,521
  • 3
  • 39
  • 45