Search code examples
powershellwindows-shell

FolderItem.Name does return name without file extension


  1. Create file, lets say at C:\randomname\file.txt,
  2. Now run the following script via PowerShell:

    $shell = new-object -com shell.application  
    $folder = $shell.NameSpace("C:\randomname")  
    $folder.Items() | where {$_.Name -eq "file.txt"}
    
  3. Observe no output is produced which is rather unexpected.

Any idea how to resolve this situation in a reasonable manner other than modifying Windows settings?

EDIT:

To prevent confusion, this is just a stripped down version of my actual problem. Reason why I am using shell.application and not Get-ChildItem is that my randomname folder is actually zipped, i.e. I have randomname.zip and my actual code looks like this:

$shell = new-object -com shell.application  
$zip = $shell.NameSpace("C:\randomname.zip")  
$folder = $zip.Items() | where {$_.Name -eq "randomname"}
$folder.GetFolder.Items() | where {$_.Name -eq "file.txt"}

Solution

  • FolderItem.Name return value depends on the value of particular Windows setting. Try the following:

    1. Open Control Panel,
    2. Folder Options, View tab,
    3. Uncheck Hide extensions for known file types.

    Re-run the script and you will see the expected output:

    Application : System.__ComObject
    Parent : System.__ComObject
    Name : file.txt
    Path : C:\randomname\file.txt
    ...

    I was trying to write a portable script but after finding out how Name works this seems rather hard as I have no control over Windows settings of our customers and there is nothing like FullName for FolderItem so I can't figure out the reliable way out.

    EDIT:

    Based on suggestion from Nick Sedgewick, that .Path always returns filename with extension, unlike .Name, I was able to create a working workaround which does not depend on Windows settings and looks like this:

    $shell = new-object -com shell.application  
    $folder = $shell.NameSpace("C:\")  
    $folder.Items() | where {(split-path $_.Path -leaf) -eq "file.txt"}