none
Powershell Remove all text after second last instance of \ RRS feed

  • Question

  • Hi Guys ,

    I have some code

    Text
    $s = "c:\programfiles\tv\version8\uninstall.exe"
    $s.Substring(0, $s.lastIndexOf('\'))
    echo $s
    

    when it echos, it shows
    c:\programfiles\tv\version8\

    Does anyone know how to get

    c:\programfiles\tv
    + 1 or adding numbers does not really seem to be working to the index
    Regards
    Monday, December 7, 2015 8:45 AM

Answers

  • Why?

    PS > $f=[io.fileinfo]'c:\programfiles\tv\version8\uninstall.exe'
    PS > $f.Directory.Parent.Fullname
    c:\programfiles\tv
    PS >


    \_(ツ)_/

    • Marked as answer by johnlee87 Tuesday, December 8, 2015 12:21 AM
    Monday, December 7, 2015 9:04 AM

All replies

  • Why?

    PS > $f=[io.fileinfo]'c:\programfiles\tv\version8\uninstall.exe'
    PS > $f.Directory.Parent.Fullname
    c:\programfiles\tv
    PS >


    \_(ツ)_/

    • Marked as answer by johnlee87 Tuesday, December 8, 2015 12:21 AM
    Monday, December 7, 2015 9:04 AM
  • This seems pretty useful

    but sometimes I want to reach a certain level of the folder

    it may not be c:\program files all the time

    Monday, December 7, 2015 9:29 AM
  • Well, you could break your entire string into an array of strings using the split method from the String Object. I use 99, because that number is higher than any number of directories you might possibly use.

    PS> $s.Split('\',99)
    c:
    programfiles
    tv
    version8
    uninstall.exe
    

    Then I rejoin them using the level you desire.

    PS> $a[0..3] -join "\"
    c:\programfiles\tv\version8

    or
    PS> $a[0..2] -join "\"
    c:\programfiles\tv

    Monday, December 7, 2015 11:25 AM
  • or you could just use Split-Path over and over.

    PS> $s = "c:\programfiles\tv\version8\uninstall.exe"
    
    PS> $t = $s | Split-Path 
    
    PS> $t
    c:\programfiles\tv\version8
    
    PS> $u = $t | Split-Path
     
    PS> $u 
    c:\programfiles\tv
     
    

    Monday, December 7, 2015 11:30 AM
  • sorry, first line should have established the $a variable before used in the second and third paragraphs

    PS> $a = $s.Split('\',99)
    c:
    programfiles
    tv
    version8
    uninstall.exe

    Monday, December 7, 2015 1:00 PM
  • The 99 parameter to the Split method is unnecessary:


    PS C:\> "c:\program files\tv\version8\uninstall.exe".Split('\')
    c:
    program files
    tv
    version8
    uninstall.exe
    

    You can also use the -split operator:


    PS C:\> "c:\program files\tv\version8\uninstall.exe" -split '\\'
    c:
    program files
    tv
    version8
    uninstall.exe
    

    You have to write '\\' if you use the -split operator because it uses a regular expression instead of a simple character or string.

    -- Bill Stewart [Bill_Stewart]

    Monday, December 7, 2015 3:49 PM
    Moderator
  • Won't work!


    \_(ツ)_/

    Tuesday, December 8, 2015 12:57 AM