Read text after last backslash

2020-03-21 10:13发布

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?

标签: powershell
4条回答
家丑人穷心不美
2楼-- · 2020-03-21 10:52

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

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

This uses two backslashes as backslash is a regex special character (escape) so the first slash is escaping the second.

查看更多
欢心
3楼-- · 2020-03-21 11:02

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

$data=Get-Content "C:\temp\users.txt"
$name=[System.IO.Path]::GetFileName($data)
查看更多
The star\"
4楼-- · 2020-03-21 11:04

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

$user = $data -replace '.*\\'
查看更多
迷人小祖宗
5楼-- · 2020-03-21 11:13

$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) {...}.

查看更多
登录 后发表回答