How to get parent folder name in powershell?

This topic contains 3 replies, has 2 voices, and was last updated by  Rishabh Verma 9 months, 2 weeks ago.

  • Author
    Posts
  • #65817

    Rishabh Verma
    Participant

    I want just the last folder name. Example
    Folder1->Folder2->file.txt
    Or
    C:\Folder1\Folder2\file.txt

    I want just Folder2 as output result.

    What i'm currently doing is

    $names = Get-ChildItem -recurse -Filter "*.txt" -Name
    Foreach(name in names){
    $fileBaseName = [System.IO.Path]::GetDirectoryName("$name")
    }
    

    This code returns result as
    Folder1\Folder2

    I just want Folder1

  • #65820

    Olaf Soyk
    Participant
    Split-Path -Path 'Your Folder' -Parent

    or

    Get-Item -Path 'Your Folder' | Select-Object Parent
    • #65821

      Rishabh Verma
      Participant
      Split-Path -Path 'Your Folder' -Parent
      

      and

      Get-Item -Path 'Your Folder' | Select-Object Parent
      

      giving same result as

      $fileBaseName = [System.IO.Path]::GetDirectoryName("$name")
      

      I just want the current folder name.

    • #65823

      Rishabh Verma
      Participant

      This Code

      Split-Path (Split-Path "$name" -Parent) -Leaf
      

      Worked for me. Thanks

You must be logged in to reply to this topic.