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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With