6

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

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

Saeid Amini
  • 1,313
  • 5
  • 16
  • 26
  • Does this answer your question? [Extract the filename from a path](https://stackoverflow.com/questions/35813186/extract-the-filename-from-a-path) – cachius Apr 28 '22 at 23:18

2 Answers2

4

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 :)

ajinkya
  • 334
  • 3
  • 15
0

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)

Ando Jurai
  • 1,003
  • 2
  • 14
  • 29