Batch or PowerShell: How to get the last word from string? - string

Here is my scenario:
I have a text file containing lot of lines. Each line is a path to a folder.
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 last child folder's name for each line and use it to create a folder link:
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 have tried this:
$a="C:\Program Files (x86)\Microsoft Office\Office15"
$a.Split()[-1]
With the result:
Office\Office15
I also tried:
$a.Split("`t",[System.StringSplitOptions]::RemoveEmptyEntries)[-1]
And the result is:
5
How do I get the last word of each line or word after last \ by using Batch or PowerShell?

I assume those folders all already exist, if so there's a completely different way to consider:
Get-Content "000.txt" | Get-Item | foreach-object {
cmd /c mklink /J $_.Name $_.FullName
}
So for each folder name you get the DirectoryInfo object associated with that folder. Then you can directly extract the last part of the path from the Name property.
This also has the advantage that you'll get an error if any of the target folders don't exist before you attempt to link to it.

You were close, but forgot to specify the character you would like to split the string on, so it defaults to space:
$a="C:\Program Files (x86)\Microsoft Office\Office15"
$a.Split('\')[-1]

Here is another simple way to do it in batch
#echo off
for /f "delims=" %%a in (000.txt) do (
mklink /j "%%~na" "%%~fa"
)

Using Batch - Take a look at the for command and string manipulation. You could 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"
)
This script loops through the text document (I've used 000.txt, could change this to a variable), each time setting the variable dir to the current line, which we are assuming is a directory path. It then prepares the string for processing by the for command (without the /f switch to loop through at each space character) by replacing all spaces with / (a character that a directory name could not contain) and all \ characters with a space (so that there is now a space between each directory name). The for loop then sets the variable ldir to the last directory name.

PowerShell has a dedicated utility for splitting paths into their parent path (directory prefix) or leaf component (filename / directory name): Split-Path.
Split-Path -Leaf returns the last path component only, which enables the following solution:
Get-Content 000.txt | ForEach-Object { cmd /c mklink /j (Split-Path -Leaf $_) $_ }
Note the need to use cmd /c, because mklink is a command internal to cmd.exe.

Related

How to loop through a directory and skip folders containing a specific string?

I am currently scanning an entire directory, copying an exe over and running it in each folder. This exe converts certain log files within each folder. However, half the directories don't contain any log files and it seems like a waste to move into each of those folders and run an exe that does nothing. An example of some folder names:
0075D-S10
0075D-S10-EVT
0132C-S10
0132C-S10-EVT
and so on...
I basically only need to copy the executable into the folders that don't contain EVT in the name. These just contain evtx files that aren't important to me at the moment.
Here is a snippet of my batch file and what it is doing:
set back=%cd%
set current_dir=%cd%
setlocal EnableDelayedExpansion
for /d %%i in ("%current_dir%\*") do (
copy LogCsv.exe "%%i" >NULL
cd "%%i"
LogCsv.exe
)
cd %back%
Really my first time just using Batch files and I've been exploring answers on here, but couldn't find a solution to this particular problem. How can I loop this directory, excluding any folders containing the "EVT" string in their name?
Thanks for taking time to assist!
Well, you can use findstr /v to exclude certain values from search results.
#echo off
set back=%cd%
set current_dir=%cd%
for /f %%i in ('dir /b /ad %current_dir%\* ^| findstr /v EVT') do (
copy LogCsv.exe "%%i" >NUL
cd "%%i"
LogCsv.exe
cd %back%
)
Also note, you need to pipe to nul not null

Search for a file and open the path in CMD

I would like to achieve the following in CMD:
Will search for a specific filename - This I know how to do, with dir /s filename
Once found it will bring me to that path.
Example: I am now on C:\, if that file was found in C:\test then it will open C:\test in command prompt.
Alternatively, I would like just to copy the found file to a path I will specify. I just don't know how to do it, since I don't know the path where the file will be stored (it's different every time).
Thanks in advance!
I'm a liitle confused with your question but I will try to walk you through a batch code I wrote to help you with this.
dir /b /s "test.txt" > "%userprofile%/Desktop/result.txt"
::find the file path to the file you want to find and insert it in a .txt file
::you made called result.txt (also %userprofile% is a variable that brings you to
::your user directory ex C:/users/admin)
for /F "tokens=*" %%A in (%userprofile%/desktop/result.txt) do (
set var1=%%A
)
::set the variable var1 equal to the first (well... only) line in the file.
::I could explain what that for loop means in detail but just remember that %%A
::is a variable set from what was found when looping through the result.txt.
xcopy /s "%var1%" "C:/wherever/you/want/it/to/go"
did this help??

Move non-archived files and set their attribute to archived in destinaton directory

I am doing an autoorganizing CMD that puts all desktop files into their respective folders. I wish a code that moved files from a folder to it's parent only if they weren't archived (archived attribute), and then archived the files in the other dir. In the least lines possible.
An example of unfinished code, replace "only move files if archived" with the code I need...
"only move files if archived"
attrib +a ..\*.*
Use robocopy.
/ia: processes files with the specified attributes only:
robocopy "source-folder" "destination-folder1" /ia:a /move
/xa: excludes files with the specified attributes:
robocopy "source-folder" "destination-folder2" /xa:a /move
To get the desktop folder into %desktop% variable:
for /f "skip=2 tokens=2*" %%a in (
'reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
^ /v Desktop'
) do call set desktop=%%b

what is Batch file (.bat) equivalent for if [-f $path ] [duplicate]

I have to create a .BAT file that does this:
If C:\myprogram\sync\data.handler exists, exit;
If C:\myprogram\html\data.sql does not exist, exit;
In C:\myprogram\sync\ delete all files and folders except (test, test3 and test2)
Copy C:\myprogram\html\data.sql to C:\myprogram\sync\
Call other batch file with option sync.bat myprogram.ini.
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You can use IF EXIST to check for a file:
IF EXIST "filename" (
REM Do one thing
) ELSE (
REM Do another thing
)
If you do not need an "else", you can do something like this:
set __myVariable=
IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt
IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt
set __myVariable=
Here's a working example of searching for a file or a folder:
REM setup
echo "some text" > filename
mkdir "foldername"
REM finds file
IF EXIST "filename" (
ECHO file filename exists
) ELSE (
ECHO file filename does not exist
)
REM does not find file
IF EXIST "filename2.txt" (
ECHO file filename2.txt exists
) ELSE (
ECHO file filename2.txt does not exist
)
REM folders must have a trailing backslash
REM finds folder
IF EXIST "foldername\" (
ECHO folder foldername exists
) ELSE (
ECHO folder foldername does not exist
)
REM does not find folder
IF EXIST "filename\" (
ECHO folder filename exists
) ELSE (
ECHO folder filename does not exist
)
Here is a good example on how to do a command if a file does or does not exist:
if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"
Use the XCOPY command:
xcopy "C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync\"
I will explain what the /c /d /h /e /i /y means:
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H Copies hidden and system files also.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
`To see all the commands type`xcopy /? in cmd
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.ini
If it was in the Bash environment it was easy for me, but I do not
know how to test if a file or folder exists and if it is a file or
folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
Type IF /? to get help about if, it clearly explains how to use IF EXIST.
To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one
Finally copying just means calling COPY and calling another bat file can be done like this:
MYOTHERBATFILE.BAT sync.bat myprogram.ini

move files name in excel to a specific folder

I am trying to write a batch file that reads from excel file. then move them to a specique folder.
lets say in the excel , there are:
111.txt
222.txt
333.txt
512.txt
I want a batch file that move files into a specific directory that have the above names.
how can I achieve that ?
(I am using xp , and I the directory is D:)
cd /d "d:\files"
for /f %%i in ("C:\where the file resides\file.csv") do (
echo move "%%i" "D:\New\"
)
remove the echo if output seems ok

Resources