Package or PowerShell: how to get the last word from a string?

Here is my scenario:

I have a text file containing many lines. Each line is a folder path.

Example: 000.txt

 C:\Program Files (x86)\Microsoft Office\Office15
 C:\Program Files (x86)\Common Files\Adobe\Acrobat
 C:\Program Files (x86)\Common Files\Blizzard Entertainment

I need to find a way to get the name of the last child folder for each row and use it to create a link to the folder:

d:\>mklink /j office15 "C:\Program Files (x86)\Microsoft Office\Office15"
d:\>mklink /j acrobat "C:\Program Files (x86)\Common Files\Adobe\Acrobat"
d:\>mklink /j "Blizzard Entertainment" "C:\Program Files (x86)\Common Files\Blizzard Entertainment"

I tried this:

$a="C:\Program Files (x86)\Microsoft Office\Office15"
$a.Split()[-1]

As a result:

Office\Office15

I also tried:

$a.Split("`t",[System.StringSplitOptions]::RemoveEmptyEntries)[-1]

And the result:

5

How to get the last word of each line or word after the last \using Batch or PowerShell?

+3
source share
5 answers

Using Batch - Look at command forand line control. You can do something like the following -

@echo off
setLocal enableDelayedExpansion
for /f "delims=" %%a in (000.txt) do (
    set dir=%%a
    set dir=!dir: =/!
    set dir=!dir:\= !
    for %%b in (!dir!) do set ldir=%%b
    echo !ldir:/= !
    mklink /j "!ldir:/= !" "%%a"
)

script ( 000.txt, ), , dir , , , for ( /f ) / (, ), \ ( ). for ldir .

+1

, , :

Get-Content "000.txt" | Get-Item | foreach-object {
    cmd /c mklink /J $_.Name $_.FullName
}

, DirectoryInfo, . Name.

, , - , .

+7

, , , :

 $a="C:\Program Files (x86)\Microsoft Office\Office15"
 $a.Split('\')[-1]
+6

@echo off
for /f "delims=" %%a in (000.txt) do (
  mklink /j "%%~na" "%%~fa"
)
+4

PowerShell ( ) ( /): Split-Path.

Split-Path -Leaf , :

Get-Content 000.txt | ForEach-Object { cmd /c mklink /j (Split-Path -Leaf $_) $_ }

cmd /c, mklink cmd.exe.

0

All Articles