Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text after last backslash

Tags:

powershell

I am would like to read in the text after the last backslash from my text file. Currently I have:

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

The users.txt file contains path from users home directories

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

How can I pick out the users account (user1.test) name at the end of the line of text so I can use it as a variable?

like image 252
Alan Brooke Avatar asked May 11 '17 12:05

Alan Brooke


3 Answers

You can use a simple regex to remove everything until and including the last slash:

$user = $data -replace '.*\\'
like image 193
Martin Brandl Avatar answered Oct 29 '22 00:10

Martin Brandl


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

$data=Get-Content "C:\temp\users.txt"
$name=[System.IO.Path]::GetFileName($data)
like image 37
Ocaso Protal Avatar answered Oct 29 '22 01:10

Ocaso Protal


$HomeDirArray = Get-Content "C:\temp\users.txt" | Split-Path -Leaf will give you an array that can be iterated through using ForEach (e.g., ForEach ($User in $HomeDirArray) {...}.

like image 41
Jeff Zeitlin Avatar answered Oct 29 '22 01:10

Jeff Zeitlin