Read text after the last backslash

I want to read the text after the last backslash from my text file. I currently have:

$data=Get-Content "C:\temp\users.txt"

      

The users.txt file contains the path from the users home directories

\\myserver.home.com\users\user1.test

      

How can I select the user account name (user1.test) at the end of the line of text so that I can use it as a variable?

+3


source to share


4 answers


Since you are dealing with file paths, you can use GetFileName :



$data=Get-Content "C:\temp\users.txt"
$name=[System.IO.Path]::GetFileName($data)

      

+5


source


You can use a simple regular expression to remove everything up to and including the last slash:



$user = $data -replace '.*\\'

      

+4


source


$HomeDirArray = Get-Content "C:\temp\users.txt" | Split-Path -Leaf

will give you an array that can be iterated over with ForEach

(eg ForEach ($User in $HomeDirArray) {...}

.

+4


source


You can use Split and [-1] to get the line after the last backslash:

$data = Get-Content "C:\temp\users.txt"
$file = ($data -split '\\')[-1]

      

This uses two backslashes, since the backslash is a special regex character (escape), so the first slash escapes the second.

+3


source







All Articles