Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating DOS batch file to PowerShell

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.

like image 346
user1075715 Avatar asked Dec 01 '11 15:12

user1075715


People also ask

How do I convert a batch file to a PowerShell script?

A Batch script that doesn't use Batch commands is always convertible to PowerShell by just changing the . cmd/. bat to a . ps1 ending, regardless of length or impact.

How do I convert command prompt to PowerShell?

For those who prefer using Command Prompt, you can opt out of the Windows Logo Key + X change by opening Settings > Personalization > Taskbar, and turning off, Replace Command Prompt with Windows PowerShell in the menu when I right-click the start button or press Windows key+X.

Do batch files work in PowerShell?

PowerShell batch files are also useful with Third-party software like BladeLogic which doesn't directly support the PowerShell extension but supports the batch files. In such a case we can run a batch job to execute PowerShell commands remotely.


1 Answers

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

like image 65
Lou Franco Avatar answered Sep 27 '22 22:09

Lou Franco