'How do I get a file path without filename in PowerShell?

I have C:\Temp\MyFolder\mytextfile.txt in a variable called $file

I want C:\Temp\MyFolder\ in another variable.



Solution 1:[1]

see Extract the filename from a path

You could have found this using:

   $file.psobject.properties

or

   $file | get-member -membertype properties

you can obtain your result in different forms there:

   $file.PSParentPath
   $file.Directory
   $file.DirectoryName

or using

   $file | Select-object DirectoryName

or

   $file | select DirectoryName

(you can add -ExpandProperties to these before DirectoryName to have an output as base property type which is String here)

Solution 2:[2]

This is quite simple You can use this piece of code to do it:

  • If you want to extract file path from the your $file variable :

    $file = 'C:\Temp\MyFolder\mytextfile.txt'
    
    $myFilePath = Split-Path $file -Parent
    
    $myFilePath = $myFilePath+'\'
    
    Write-Host $myFilePath
    
  • If you want to extract only file name then,

    $file = 'C:\Temp\MyFolder\mytextfile.txt'
    
    $myFileName = Split-Path $file -leaf
    
    Write-Host $myFileName
    

I know this is a old question but still, If you find this answer helpful please mark this as accepted, Thank you Happy coding :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ando Jurai
Solution 2 ajinkya