6

I am trying to translate a .bat file to PowerShell and having trouble with understanding what a few snippets of code is doing:

set MY_VARIABLE = "some\path\here"  
"!MY_VARIABLE:\=/!"

What is line 2 above doing? Specially, I dont understand what the :\=/ is doing since I have seen the variable else where in the code being referenced like !MY_VARIABLE!.

The other point of confusion is the below code.

set SOME_VARIABLE=!SOME_ARGUMENTS:\=\\!  
set SOME_VARIABLE=!SOME_ARGUMENTS:"=\"!

Also, can you tell me what is going on in lines 3 and 4 above as well?

What would the below variables translate into PowerShell as well?

set TN0=%~n0  
set TDP0=%~dp0  
set STAR=%*

Any help on this is much appreciated. Thanks.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52

3 Answers3

4

The !var:find=replace! is string substitution for a variable that is delay-expanded.

http://www.robvanderwoude.com/ntset.php#StrSubst

When you use ! instead of % for a variable, you want DOS to do the variable replacement at execution time (which is probably what you think it does with %, but it doesn't). With %, the variable is substituted at the point that the command is parsed (before it's run) -- so if the variable changes as part of the command, it won't be seen. I think some switch to using ! all of the time, because it gives "normal" behavior.

You can read more about delayed expansion here

http://www.robvanderwoude.com/ntset.php#DelayedExpansion

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
3

The first two set variableName= commands use modifiers to expand on the name of the batch file, represented as %0.

%~n0 expands it to a file name, and
%~dp0 expands it to include a drive letter and path.

The final one, %*, represents all arguments passed to the batch file.

Additional information can be found in answers here or here.

Dave M
  • 1,302
  • 1
  • 16
  • 28
1

Exclamation points (!) i n DOS batch files reference the intermediate value, useful if you are in a for-loop. If you were to use a % instead (in a loop), it would return the same value over and over.

Lines 3 and 4 are setting "SOME_VARIABLE" to the intermediate value of "SOME_ARGUMENTS:\=\" and SOME_ARGUMENTS:"=\", respectively. Again, I'm guessing that these lines are from a loop.

As for the variable assignments, Powershell variable assignments work like this:

    $myVariable = "my string"

~dp0 (in DOS batch) translates into the path (with drive letter) of the current bat file. You can get that in Powershell by doing a "get-location".

Why someone would need to set a variable for STAR(*) is beyond me, so I'm assuming there was some encoding issue or other reason that they couldn't just use an asterisk.

~n0 I'm not sure about; maybe someone else knows what that one is.

Aaron
  • 55,518
  • 11
  • 116
  • 132