PowerShell for N00bs: $env:temp vs. %TEMP%
A while ago, we snuck in something.
PSH> dir $env:temp | less
$env:temp is PowerShell's way of accessing the original environment variables, the stuff we get when we type 'set' at a cmd.exe prompt. 'set' in PowerShell is an alias for Set-Variable, so it doesn't do the same thing. To get the same output, type 'cmd /c set' in a PowerShell prompt.
Well, that's cheating, a bit. What we're doing is starting a cmd.exe session, and having it run the cmd.exe set command. How do we do it in powershell?
PSH> dir env:
What? We have a disk drive named 'env" and that contains our environment variables? Not quite. env: is a PowerShell Provider. If anything, the c: drive is another PSProvider. Under PowerShell, all data is stored in some Provider or another.
We've been using standard cmd.exe commands on our files in PowerShell, right? Stuff like 'del' and 'copy' and 'type', right? Well, because PowerShell is designed in an Object-Oriented fashion, commands that work on files will also work on ... environment variables?
Yes. We can delete an environment variable by
PSH> del env:temp
We get nothing back. In fact, if we run 'cmd /c set temp', we'll see that the cmd.exe session we started inherits the environment variables of the current PowerShell session, which lacks a %TEMP% variable.
PSH> cmd /c set temp
Environment variable temp not defined
Let's close this PowerShell window and start a new one.
Notice that it's set again. We deleted the %TEMP% environment variable in that window, but it didn't take effect in all windows.
Onto the value of the environment variable. We know "$env:temp" echos the value of %TEMP%. That's because it's a variable, and $variableName displays the variable's value. But, we said before env: is a PSProvider and c: is also a PSProvider. Does this mean we can display a file just like it was a variable?
PSH> type C:\autoexec.bat
REM Dummy file for NTVDM
Unexpected token '\autoexec.bat' in expression or statement.
At line:1 char:17
+ $c:\autoexec.bat <<<<
+ CategoryInfo : ParserError: (\autoexec.bat:String) , ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Oops, I guess not. Wait. Let's look at the error message. "Unexpected token '\autoexec.bat' in expression or statement."
REM Dummy file for NTVDM
(Personally, I prefer Get-Content. It makes the code more readable.)
So we've learned that PowerShell exposes the system (and user) environment variables as a 'drive'. Actually it's a PSProvider, but we think of it as a drive because that's how drives are also exposed, and we're most familiar with drives.