April 6, 2020 by Kenneth Fisher
The other day Kendra Little (blog|twitter) mentioned that she was trying to get a command in Powershell working. Specifically one that used an environment variable (%programfiles(x86)%). Shockingly (not) she figured that part out pretty quickly but I still thought it would make an interesting subject for a blog post.
Powershell is hard. I tried to figure out the equivalent of this (which works in a cmd prompt) and… oy.
"%programfiles(x86)%Red GateSQL Compare 14SQLCompare.exe" /scripts1:"C:agent_work1State" /sca2:"C:agent_work1MigrationsDemoWorkflow_Migrations.sqlproj"
— Kendra Little (@Kendra_Little) March 30, 2020
So to start, in batch, cmdshell, or DOS (whatever you want to call it) you can use certain environment variables in your code. For example %programfiles(x86)% that Kendra mentioned will tell you the location of the Program Files (x86) directory. This is handy because not every system uses C:\Program Files (x86) for that particular set of directories. Some other ones I found include the path for the system and temp directories. Interestingly I did some research and I wasn’t able to find a list of this type of environment variable. They appear to be stored in the registry but weren’t easy to find.
Powershell makes this pretty darn easy. All environment variables are under env:. So you can get that same variable this way: (Technically this is a different variable but I couldn’t figure out how to get the ProgramFiles(x86) to work. The parenthesis kept giving me issues.)
And Powershell being what it is getting the list here turned out to be pretty easy:
Set-Location Env: Get-ChildItem
From what I can tell these same variables are also available in cmdshell.