FolderItem.Name does return name without file extension

1.9k views Asked by At
  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"}
2

There are 2 answers

2
Michal Hosala On BEST ANSWER

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"}
1
Nick Sedgwick On

A Namespace Item has a PATH property, which returns full path and filename for files, and always includes the filename extension, whether the user has 'hide filename extensions' set or not.

So, use 'Path' instead of 'Name' and either write a function to pass $_.Path to which can the extract the filename part, or use an equivalent of the LIKE operator if there is one in powershell