Read text after last backslash

前端 未结 4 1165
生来不讨喜
生来不讨喜 2021-01-12 18:08

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\"
<
相关标签:
4条回答
  • 2021-01-12 18:19

    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.

    0 讨论(0)
  • 2021-01-12 18:25

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

    0 讨论(0)
  • 2021-01-12 18:27

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

    $user = $data -replace '.*\\'
    
    0 讨论(0)
  • 2021-01-12 18:31

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

    $data=Get-Content "C:\temp\users.txt"
    $name=[System.IO.Path]::GetFileName($data)
    
    0 讨论(0)
提交回复
热议问题