Search code examples
powershellfilesystemsmetadatacomobject

Powershell Shell.Application object not finding folder


I am trying to get metadata from files. I am using the code example found here.

Below is some sample code that I am using to try and access ANY folder, being that I don't seem to be able to do so:

$TheThing = "C:\Windows"

$folder = {$TheThing}

foreach($sFolder in $folder) 
  { 
   $a = 0 
   $objShell = New-Object -ComObject Shell.Application 
   $objFolder = $objShell.NameSpace($folder)

   foreach ($File in $objFolder.items()) 
    {  
     $FileMetaData = New-Object PSOBJECT 
      for ($a ; $a  -le 266; $a++) 
       {  
         if($objFolder.getDetailsOf($File, $a)) 
           { 
             $hash += @{$($objFolder.getDetailsOf($objFolder.items, $a))  = 
                   $($objFolder.getDetailsOf($File, $a)) } 
            $FileMetaData | Add-Member $hash 
            $hash.clear()  
           } #end if 
       } #end for  
     $a=0 
     $FileMetaData 
    } #end foreach $file 
  } #end foreach $sfolder 

The line:

$objFolder = $objShell.NameSpace($folder)

...doesn't actually do anything. In fact, when the code drops into the foreach loop, it fails with a "You cannot call a method on a null-valued expression" error on the line:

foreach ($File in $objFolder.items()) 

Am I missing something?


Solution

  • This line is causing your issue:

    $folder = {$TheThing}
    

    It needs to be:

    $folder = $TheThing
    

    By using { } you make it a scriptblock, where as you just need it to be a string with the path that you want to interrogate.

    You also might as well just put the path there instead of having two variables for a single purpose.