header image

COM pt 3–More shell

Posted by: | January 29, 2011 | 1 Comment |

Last time we looked at the Environment parameterized property

If you ran the script in part two the output would have contained things like


We need to be able to resolve the variable %SystemRoot% part to the full path

$wshell = New-Object -ComObject "WScript.Shell"
, "User", "Process", "Volatile" |
foreach {
 $envars  = $wshell.Environment($($_))
 foreach ($envar in $envars){
   if ($envar -match "%.*%"){
   $s = ($envar -split "%")[1]
   $exp = $wshell.ExpandEnvironmentStrings("%$s%")
   $envar.Replace("%$s%", $exp)
  else {$envar }


We can take the script from part 2 and modify it slightly. Once we have the environmental variables for each area we loop through them and find those that contain the pattern “%.%”. This is a simple regular expression (I only do simple regex.  Maybe I’ll get more adventurous after the March UG group when we have a guest speaker on regex) that looks for two % signs separated by some characters.

If we find that we split on the % and take the second element – push it through the ExpandEnvironemtStrings method and plus the result back into the environmental variable.

under: COM, PowerShellV2

1 Comment

  1. By: Nagesh on June 11, 2012 at 8:39 am      

    Great Post.. I just got some clarity on this bevahior from MSFT. Apparently, this is the default bevahior even when a backup is compressed. Backup will try to extend disk files to its full backup size during backup. But when the backups process completes it only takes the needed space.According to MSFT, this has been filed as a bug but the fix has been postponed. To work around this issue, it has been suggested to use Trace flag 3042. This Trace flag will disable the pre-extension of the backup files and we would not see the pre-extension of backup files during initial stages of backup.So you enable trace flag 3042 in the beginning of the backup script and disable it at the end of the script.Example:DBCC TRACEON (3042, -1); Turn on trace flagBACKUP DATABASE [mydb] TO DISK …;BACKUP DATABASE [mydb] TO DISK …;DBCC TRACEOFF (3042, -1); Turn off trace flag