Remove strings from particular index in a line using powershell - powershell

My text file contents similar to following lines
xcopy Source Destination /y /r /Q
xcopy Source Destination /y /r
I am trying to remove all the characters after Desination.
I was trying with Indexof method and remove method. But i did not find a right answer
I tried the find the third occurence of Whitespace and remove from it. but it doesn't works.
$index=$line.IndexOf(" ",3)
$line=$line.RemoveAt($index)
Can some one helps me to achieve this using powershell

I'm guessing your actual file will have paths such as this:
xcopy "C:\Folder with space" "C:\Folder 2 with space" /y /r /Q
So you can remove the xcopy arguments with a search/replace regular expression such as this:
'xcopy "C:\Folder with space" "C:\Folder 2 with space" /y /r /Q' -replace '/[\w]' , ''
The result is:
xcopy "C:\Folder with space" "C:\Folder 2 with space"
This way you don't have to worry about how many spaces are before the xcopy parameters. The parameters will be removed regardless of how many spaces came before them.
The regular expression matches and removes text with a forward slash followed by a character class representing a word character.

[Regex]::Replace("xcopy Source Destination /y /r /Q","^(xcopy) +([^ ]+) +([^ ]+).*$","`$1 `$2 `$3") should do the trick.

Related

Renaming incrementing integer name to incrementing integer

can you show me a way to solve following problem with Powershell or CMD?
This is my file names in folder.
002.mp3
003.mp3
.
.
.
604.mp3
I want to change that numbers to;
001.mp3
002.mp3
003.mp3
.
.
.
603.mp3
But important thing is, it has to be like that
002.mp3 to 001.mp3
003.mp3 to 002.mp3
...
...
...
604.mp3 to 603.mp3
thank you very much.
You can do the following:
$files = Get-ChildItem -Path "C:\PathToMP3Files\[0-6][0-9][0-9].mp3" -File
$files | Rename-Item -NewName {"{0:D3}.mp3" -f ([int]$_.BaseName - 1)} -whatif
Just remove the -whatif parameter to perform the rename if you are satisfied with the results.
Explanation:
The -Path parameter of Get-ChildItem supports wildcards. Using a wildcard range [0-6] (one character from the set 0 to 6), you can narrow down your target items.
Since New-Item's -NewName supports delay-script binding, you can pipe your FileInfo objects directly into the command. The -NewName parameter manipulates the Name property of the object. The code above is using BaseName, which is the Name without the extension, because it is an easy way to perform digit increase.
-f is the string format operator. It performs a substitution of {number} values within a string. The number corresponds to an item's index in the collection provided to the right of the -f.
This is simpler in a Batch file, and run faster than PS too! (just try it)
#echo off
setlocal EnableDelayedExpansion
for /F %%a in ('dir /B *.mp3') do set /A "n=1%%~Na-1" & ren "%%a" "!n:~1!.mp3"
Yoy may even do it directly at the command prompt with no need of a .bat file; just be sure that n variable does not exists (executing set "n=" before):
for /F %a in ('dir /B *.mp3') do #set /A "n=1%~Na-1" & call ren "%a" "%n:~1%.mp3"

batch add a character(s) in the middle of a filename using cmd

So I have files (mostly documents) with a file name beginning with "YYYYMMDD - Title of file.etc"
I'm wanting to change the date format to YYYY-MM-DD
I'm wanting to do a script to batch rename since I'll be doing this every now and then.
My bat code so far after a 2 days of research to no avail:
for %%a in ("*.*") do ren *.* ????-??-??*.*
pause
Any help or point to the right direction for me to look at would be really helpful. Thanks
final
rem // Loop through all matching files:
for /F "eol=| delims=" %%F in ('
dir /B /A:-D-H-S "*.*"
') do (
rem // Store the current file name and extension to variables:
set "NAME=%%~F"
rem // Enable delayed expansion to avoid trouble with `!`:
setlocal EnableDelayedExpansion
rem // Rename file by applying sub-string expansion:
ren "!NAME!" "!NAME:~,4!-!NAME:~4,2!-!NAME:~6!!EXT!"
endlocal
)
pause
You are utilising a for loop but not using its meta-variable %%a in the body then, which makes no sense.
Unfortunately, you cannot just use ren for that, because every ? in the new name represents the character of the old name at that position.
I would do it the following way:
rem // First change to the target directory:
cd /D "D:\Target\Dir"
rem // Loop through all matching files:
for /F "eol=| delims=" %%F in ('
dir /B /A:-D-H-S "*.*" ^| findstr /I "^[1-2][0-9][0-9][0-9][0-1][0-9][0-3][0-9]"
') do (
rem // Store the current file name and extension to variables:
set "NAME=%%~nF" & set "EXT=%%~xF"
rem // Enable delayed expansion to avoid trouble with `!`:
setlocal EnableDelayedExpansion
rem // Rename file by applying sub-string expansion:
ren "!NAME!!EXT!" "!NAME:~,4!-!NAME:~4,2!-!NAME:~6!!EXT!"
endlocal
)
The [findstr][cmdfnd] is used here to filter for file names that begin with eight decimal digits that could represent a date. If you do not want that simply remove everything from ^| findstr up to the end of that line.
Delayed variable expansion is needed here, because you are writing and reading variables within the same block of code. Splitting the original name at fixed character positions is done by sub-string expansion.
(How-To: Extract part of a variable (substring))
[cmdfnd]: https://ss64.com/nt/findstr.html
(FINDSTR)
RightHanded,
Maybe you should look at Powershell commands.
The following powershell command replaces spaces with underscores of all files of the current directory :
dir | rename-item -NewName {$_.name -replace " ","_"}
Source : https://www.howtogeek.com/111859/how-to-batch-rename-files-in-windows-4-ways-to-rename-multiple-files/
You can see how to modify Powershell strings here for example : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convert-string?view=powershell-5.1
Powershell will be much easier to do this. Use this:
#echo off
pushd "The Directory"
powershell -command "& {get-childitem | foreach {$NewName = $_.Name -replace '\d{8}.*', '\d{4}-\d{2}-\d{2}.*'; rename-item -path '.\$_.Name' -newname '$NewName'}}"
popd
goto :eof
You can use this as a function to rename the files to the format you want. You can call this function inside a loop FOR, if you want.
set old_filename=YYYYMMDD - Title of file.etc
:: Extract only the first 4 characters
SET yyyy=%old_filename:~0,4%
:: Skip 4 characters and then extract the next 2
SET mm=%old_filename:~4,2%
:: Skip 6 characters and then extract the next 2
SET dd=%old_filename:~6,2%
:: Skip 8 characters and then extract everything else
SET everything_else=%old_filename:~8%
:: Rename de old filename to the new
rename "%old_filename%" "%yyyy%-%mm%-%dd%%everything_else%"

Need a script to delete certain type of files in a folder based on conditions

I am having some issues with OneNote overpopulating the drive with .onetoc2 files. I need a script or cmd command that deletes these files only if the folder that it's contained in does not have a .one file. I need this run for the entire directory.
I have a delete prompt that deletes all the files but I don't know how to get the conditional aspect of it accomplished.
DEL /S /Q c:\Folders \*.onetoc2
something like this could work in powershell
$folder
if (!(dir $folder *.one)) {
dir $folder *.onetoc2 | % {del $_.FullName -WhatIf}
}
for /f "delims=" %A in ('dir /b "c:\folder\*.onetoc2"') do if not exist "%~dpA%~nA.one" echo del "%A"
Use %%A in batch. Remove the echo statement to allow it to delete.

Replace Single Quotes (') in Filenames

I received a good suggestion in another thread to support the removal/replacement of specific characters from filenames in a directory structure. Works as expected for common ascii characters (like &).
PowerShell (works fine to remove & character from filenames):
powershell.exe -c "Get-ChildItem 'c:\Media\Downloads' -Filter '*&*' -Recurse | Rename-Item -NewName {$_.name -replace '&','' }"
I also need remove single quotes from some files: Example: mark's_file.txt.
I've tried a few variants without success. I think I am running into a punctuation issue I am unable sort out. I also tried using a variable = char(39) and adding to the string. No luck.
Any ideas to accomplish?
Note: Would like a self contained batch file approach, vs calling an external .ps1 file.
A Batch file also works fine to remove both & and ' characters from filenames:
#echo off
setlocal EnableDelayedExpansion
rem Remove "&" characters:
for /R "c:\Media\Downloads" %%a in ("*&*") do (
set "fileName=%%~NXa"
ren "%%a" "!filename:&=!"
)
rem Remove "'" characters:
for /R "c:\Media\Downloads" %%a in ("*'*") do (
set "fileName=%%~NXa"
ren "%%a" "!filename:'=!"
)
... but the Batch file start run much faster than the PS one!

Robocopy for long paths with /mir switch changed destination to root and nuked machine

My purpose was to copy files with long paths (+255 char) and spaces in the folder path from a computer to a server with an analogus folder already in place (needed to maintain folder structure). Below is an example of the script:
robocopy "c:\long path\with spaces" "\\servername\long path\with spaces" filename.html /MIR /R:5 /LOG+:\\server\logfolder /v /NP
The result was the below log and a complete deletion of the source machine. Any thoughts?
Source : c:\long path\with spaces
Dest : \
Files : filename.html
Options : /V /S /E /PURGE /MIR /NP /R:5 /W:30
I've been researching and have found no other situation. I'd absolutely love to avoid this issue in the future.
unfortunately, robocopy is going to see the "\\" as an escape sequence, and you end up with a path that's just \. you need to use /"\servername\long path\with spaces\/" for quoted UNC paths.