powershell

Get shortpath using powershell


I am trying to get shortpath using the below code in powershell. For some folders it works. For some it does not work.

$a = New-Object -ComObject Scripting.FileSystemObject 
$f = $a.GetFile("C:\Program Files\Internet Explorer") 
$f.ShortPath

I get the below error although the folders are available :

Exception calling "GetFile" with "1" argument(s): "Exception from HRESULT: 0x800A0035 (CTL_E_FILENOTFOUND)"
At C:\Misc\GetShortPath.ps1:4 char:1
+ $f = $a.GetFile("C:\Program Files\Internet Explorer")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

Can someone please help


Solution

  • Distinguish files and folders:

    $a = New-Object -ComObject Scripting.FileSystemObject 
    $f = $a.GetFile("C:\Program Files\Internet Explorer\iexplore.exe") 
    $f.ShortPath
    $f = $a.GetFolder("C:\Program Files\Internet Explorer") 
    $f.ShortPath
    

    Output:

    C:\PROGRA~1\INTERN~1\iexplore.exe
    C:\PROGRA~1\INTERN~1