Tags


Powershell

Here’s a trick I stumbled across.   Converting Environment variables (%SOMENAME%) in Powershell.

Now every Powershell person knows that using $ENV:VariableName (without the % before and after) will reveal that variable.   Very simple.

But what if it’s embedded in a path?  How about TWO or THREE?

Now I COULD figure out some Ultra cool “Convert O Matic” function or I could leverage some already existing technology.  Creating fresh is better but today, I don’t have the time.  Much like many of us.

So I was thinking “Gee, If I could somehow use the ECHO command in CMD.EXE it would work, even if it’s just to get this working”

Well you can.  Microsoft didn’t lock you out with Powershell, they gave you another TOOL to use and leverage how YOU need to use it.

CMD.EXE (and any other executable) can still be launched in Powershell.  It’s output can be captured and parsed afterwards as well.  As an added bonus, the Powershell interface will even pass it’s OWN $Variables to NON Powershell applications (Provided the content is what the application is expecting).  You can also leverage other applications like Robocopy.exe and pass Powershell $variables to them (Again, as long as the content is what they are expecting)

So keying in

CMD.EXE /?

Showed me all the parameters I needed.   I found a /C which launches a command and returns when done.

So a simple

$VariableForDos=”%SYSTEMROOT%System32driversetc”

CMD.EXE /C “ECHO $VariableForDos”

Will echo back

C:WindowsSystem32Driversetc

If I’d like this as an easy to use function

Function global:GET-DOSVARIABLE($Convert) {

$RESULTS=CMD.EXE /C “ECHO $Convert”
RETURN $RESULTS

}

The nice part is if you create this is a function, is if you DO find a more elegant solution you only need re-write the function, not your entire Shell Script.

So what does this show us?  a Few things. 

I can pass $Powershell variables to a non Powershell executable (CMD.EXE) and I can leverage and use IT’S resources rather than rebuilding them in Powershell.  

I can also use some bulit in older technology to my advantage as an Administrator.  I am not tied down to building it all from scratch in Powershell.

After all, isn’t that what it’s all about?  Making things EASIER?

The Power of Shell is in YOU

Sean
The Energized Tech
www.Powershell.ca

Advertisements