Home > OS >  How to find the directory path of a file in powershell
How to find the directory path of a file in powershell

Time:08-14

Let me tell about my scenario.

I have a file on the desktop, I don't know its full name and where is it location. I just know that file starts with "ABC" and its an .exe. So I am trying to find the path to this file with the help of a script. I've tried to use this function.

  function  findPath ($path) {

return $thePath = Get-ChildItem -Path $path -Filter '*ABC*.exe'  -Recurse | % { $_.FullName }

}

When I call the this function this fun gives me a string input like:

    C:\Users\UserX\Desktop\New Folder\FolderA\FolderB\1_Abc.exe

Is there anyway to reach path of :

      C:\Users\UserX\Desktop\New Folder\FolderA\FolderB\

CodePudding user response:

Split-Path -Path works for me.

CodePudding user response:

Guessing that you might be looking for the folder path of the target of a shortcut to an exxecutable. If so:

Function Get-TargetFolderPath ($LinkPath) {
    (new-object -com wscript.shell).CreateShortcut($Path).TargetPath | Split-Path
}

And, exclusively for Desktop shortcuts and URLS, this requires only the Dispaly Name of the the shortcut and works for items from both the user's Desktop folder and the Public Desktop folder:

Function Get-DesktopShortcutTargetPath ($LinkName) {
    (@((New-Object -com shell.application).NameSpace(0).Items()) | ? Name -eq $LinkName).ExtendedProperty("System.Link.TargetParsingPath") | Split-Path
}
PS > Function Get-DesktopShortcutTargetPath ($LinkName) {
>>     (@((New-Object -com shell.application).NameSpace(0).Items()) | ? Name -eq $LinkName).ExtendedProperty("System.Link.TargetParsingPath") | Split-Path
>> }
PS >
PS > Get-DesktopShortcutTargetPath 'Adobe Acrobat DC'
C:\Program Files\Adobe\Acrobat DC\Acrobat
  • Related