I’ve been working on this one issue for abut a week, and think I’m missing something obvious…I need a couple sets of eyes.
Starting with this question I researched all the links provided in the answer, and I’m running the following script, gleaned from MS Connect:
$txtPath = "c:\users\xxxxxx\desktop\cgc\tx"
$txtPath2 = "c:\users\xxxxxx\desktop\cgc\tx2"
get-childitem $txtPath | foreach {
Move-Item -literalpath $txtPath2.Name $_.Name.Replace ("]" | "[", "_")
}
Both paths exist. *\tx contains 35 *.txt files, some with square brackets in the name, some without. *\tx2 is currently empty, awaiting output files from the script.
If I’ve written my third statement properly, I’m passing each child from \tx to the function where square brackets are changed to an underscore as the file is moved and re-saved to the new location, \tx2.
Unfortunately, I get this error:
Expressions are only allowed as the first element of a pipeline.
At C:\users\xxxxxx\desktop\cgc\rni.ps1:4 char:71
+ Move-Item -literalpath $txtPath2.Name $_.Name.Replace ("]" | "[", "_" <<<< )
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline
If I’m interpreting the error correctly, something’s preventing the close paren to be recognized. Do I need some kind of escape character for the brackets? I tried using a backtick escape and backslash escape inside the quotes, but that led to the same error.
With the escape outside the quotes, I got this error.
The term '\]' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is correct and try again.
At C:\users\xxxxxx\desktop\cgc\rni.ps1:4 char:61
+ Move-Item -literalpath $txtPath2.Name $_.Name.Replace (\"]" <<<< | \"[", "_")
+ CategoryInfo : ObjectNotFound: (\]:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
What am I missing?
You got the syntax wrong:
is just nonsense. Usually it would mean “Call the
Replacemethod on$_.Namewith the return value of the following as argument: Pipe the string']'as input into the command'[', '_'”. But here lies the first problem: That’s no command, it’s an expression and that cannot work. Then the problem is that this is the argument to a cmdlet. Special rules apply here and they usually say “convert to string everything that isn’t in parentheses”. So there isn’t even a method call, you’d get the method declaration as the new file name and pass another argument that suffers from the problems described above.If I’d have to guess I’d think you want to replace square brackets by underscores. If so, then use the following: