Below is a one-line script I am writing that is causing problems when I try to add an open-paran within invoke-expression
.
Within the script, the file map.txt
contains 800 lines of 3 digit numbers. The script is intended to change the name of existing files that start with 001..400 (unique/non-repeating) by prefixing a new (unique) three digit number and space before the existing file. To do this, the a three-digit number is extracted from map.txt
to find the file I want renamed (using invoke-expression "ls $line1 (*"
and the next line in map.txt
is the number that should be prefixed to the existing file. So, if the first two lines of map.txt
are 001
and 008
, the file, 001 (additional characters).ext
(parentheses are part of file name) will be changed to 008 001 (additional characters).ext
It will execute if I remove the open-paran within invoke-expression
. However, without the open-paran within invoke-expression, when the map.txt
file comes to a number pair of 008
021
, it will try to rename the 008 001 (additional characters).ext
that has already been renamed. Adding the open-paren makes files names unique regardless of name changes that have already occurred and the script should execute as desired. That is, if I can figure out how to include an open-paren within invoke expression
. I could probably do a work around with a few lines of regex and -match
but if I can find a quick solution to include the open-paran with invoke-expression
, it would be ideal.
Thanks for your help.
for ($i=0; $i -lt 800; $i=($i+"2")) {$line1=(get-content ..\map.txt | select -index $i); $line2=(get-content ..\map.txt | select -index ($i+"1")); $old=(invoke-expression 'ls $line1 (*'); $fileold=($old.basename+$old.extension); $filenew=($line2+" "+$fileold); mv "$fileold" "$filenew"}
invoke-expression "ls $line1*"
and creating a new empty subfolder (I callednew
), I changed the move command tomv $fileold" "new\$filenew"
preventing the script from being able to act upon a file that has already been renamed. – Brian Jul 23 '20 at 2:29Invoke-Expression
cmdlet when you can simply rename the file with standard PoSh commands? theI-E
cmdlet is considered the equivalent of SQL injection in terms of risk. [2] the term "one liner" means without any line delimiters. you have 6 lines inside yourfor
loop. [grin] [3] why are you quoting the integers you are adding to your$I
variable? that is dangerous since you are adding a char to an int. yes, PoSh coerces it to an int ... but why use a char for that? – Lee_Dailey Jul 23 '20 at 14:49$line1="001";Invoke-Expression 'ls $line1 (*'
would have been a MCRE and nobody would have ever had to read/understand your file renaming stuff as it is not part of the problem. Anyway, maybe you can get some inspiration from my code below. – Thomas Jul 24 '20 at 20:50