Skip to content

Instantly share code, notes, and snippets.

@RamblingCookieMonster
Created January 17, 2015 16:09
Show Gist options
  • Save RamblingCookieMonster/1332be1e5982d4394668 to your computer and use it in GitHub Desktop.
Save RamblingCookieMonster/1332be1e5982d4394668 to your computer and use it in GitHub Desktop.
Get-UserEnvironment
<#
Fun trying to determine a current runspaces variables and modules.
In response to thise tweet: https://twitter.com/xvorsx/status/556348047022510080
I'm assuming there are a number of issues I'm not considering, this was just a morning distraction.
#>
#This would create a new runspace, get variables, modules, snapins.
#Presumably this changes based on PS version, so need dynamic method to extract it
$StandardUserEnv = [powershell]::create().addscript({
#Get modules and snapins in this clean runspace
$Modules = Get-Module | Select -ExpandProperty Name
$Snapins = Get-PSSnapin | Select -ExpandProperty Name
#Get variables in this clean runspace
#Called last to get vars like $? into session
$Variables = Get-Variable | Select -ExpandProperty Name
#Return a hashtable where we can access each.
@{
Variables = $Variables
Modules = $Modules
Snapins = $Snapins
}
}).invoke()
$UserVariables = Get-Variable -Exclude $StandardUserEnv.Variables
$UserModules = Get-Module | Select -ExpandProperty Name | Where {$StandardUserEnv.Modules -notcontains $_}
$UserSnapins = Get-PSSnapin | Select -ExpandProperty Name | Where {$StandardUserEnv.Snapins -notcontains $_}
<#
Hypothetically, you could now set up new runspaces to mimic the user environment, with a few caveats:
Variables created and maintained by modules and other external sources
Variables created and maintained by PowerShell, not present in certain conditions (e.g. LASTEXITCODE, Matches)
Variables in other scopes. If I import a module, and that module keeps configuration state in variables not exported...
In PowerShell 3 and later, UserModules will likely include modules like Microsoft.PowerShell.Management
Other stuff, need more caffeine : )
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment