How to get parent folder name in powershell?

Welcome Forums General PowerShell Q&A How to get parent folder name in powershell?

This topic contains 3 replies, has 2 voices, and was last updated by

 
Participant
1 year, 9 months ago.

  • Author
    Posts
  • #65817

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 259
    Helping Hand
    Rank: Contributor
    Split-Path -Path 'Your Folder' -Parent

    or

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

      Participant
      Points: 0
      Rank: Member
      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

      Participant
      Points: 0
      Rank: Member

      This Code

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

      Worked for me. Thanks

The topic ‘How to get parent folder name in powershell?’ is closed to new replies.