Skip to content

Instantly share code, notes, and snippets.

@JPRuskin
Created May 3, 2019 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPRuskin/5018f1195ff901ac0343f62336e25782 to your computer and use it in GitHub Desktop.
Save JPRuskin/5018f1195ff901ac0343f62336e25782 to your computer and use it in GitHub Desktop.
Export and Import Variables between PowerShell sessions (naive)
# function Export-Variable {
[CmdletBinding()]
param(
[ArgumentCompleter({
param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $BoundParams)
$Current = $BoundParams.Name
(Get-Variable).Name.Where({$_ -like "*$($WordToComplete)*" -and $_ -notin $Current})
})]
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]$Name,
[ValidateRange(1,20)]
[int]$Depth = 5,
[string]$Path = (Join-Path $env:Temp "ExportedVariables")
)
process {
switch ($PSBoundParameters.ContainsKey('Name')) {
$true {
foreach ($Variable in $Name) {
Get-Variable -Name $Variable | %{
Write-Verbose "Exporting: '$($_.Name)'"
$_ | Export-Clixml -Path "C:\Temp\Variables\$($_.Name).clixml" -Depth $Depth
}
}
}
$false {
Get-Variable | Out-GridView -PassThru | %{
Write-Verbose "Exporting: '$($_.Name)'"
$_ | Export-Clixml -Path "C:\Temp\Variables\$($_.Name).clixml" -Depth $Depth
}
}
}
}
# }
# function Import-Variable {
[CmdletBinding()]
param(
[ValidateScript({
if ((-not (Test-Path $_ -PathType Container)) -and (-not (Test-Path $_ -PathType Leaf -Include *.clixml))) {
throw "Path must be to a folder or *.clixml file"
}
$true
})]
$Path = (Join-Path $env:Temp "ExportedVariables")
)
foreach ($Var in Get-ChildItem $Path -Filter *.clixml) {
Write-Verbose "Importing '$($Var.BaseName)'"
Set-Variable -Name $Var.BaseName -Value (Import-Clixml $Var.FullName).Value
}
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment