Skip to content

Instantly share code, notes, and snippets.

@awakecoding
Created September 27, 2024 15:01
Show Gist options
  • Save awakecoding/16af80c8107bb0b2014a0ad5384709a2 to your computer and use it in GitHub Desktop.
Save awakecoding/16af80c8107bb0b2014a0ad5384709a2 to your computer and use it in GitHub Desktop.
function New-PSHostSession {
[CmdletBinding(DefaultParameterSetName = 'ById')]
param (
[Parameter(ParameterSetName = 'ById', Mandatory = $true, Position = 0)]
[int] $Id,
[Parameter(ParameterSetName = 'ByProcess', Mandatory = $true, ValueFromPipeline = $true)]
[System.Diagnostics.Process] $Process,
[Parameter(ParameterSetName = 'ByCustomPipeName', Mandatory = $true)]
[string] $CustomPipeName,
[Parameter(ParameterSetName = 'AllSets')]
[string] $AppDomainName,
[Parameter(ParameterSetName = 'AllSets')]
[int] $OpenTimeout = 2000
)
process {
if ($PSCmdlet.ParameterSetName -eq 'ById') {
$ProcessId = $Id
} elseif ($PSCmdlet.ParameterSetName -eq 'ByProcess') {
$ProcessId = $Process.Id
}
if ($PSCmdlet.ParameterSetName -eq 'ByCustomPipeName') {
$ConnectionInfo = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($CustomPipeName)
$TransportName = $CustomPipeName
} else {
$ConnectionInfo = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($ProcessId)
$TransportName = "NamedPipe:${ProcessId}"
}
$ConnectionInfo.OpenTimeout = $OpenTimeout
if ($AppDomainName) {
$ConnectionInfo.AppDomainName = $AppDomainName
} elseif ($PSCmdlet.ParameterSetName -ne 'ByCustomPipeName') {
$PSHostProcessInfo = Get-PSHostProcessInfo $ProcessId
$ConnectionInfo.AppDomainName = $PSHostProcessInfo.AppDomainName
}
$TypeTable = [System.Management.Automation.Runspaces.TypeTable]::LoadDefaultTypeFiles()
$Runspace = [RunspaceFactory]::CreateRunspace($ConnectionInfo, $Host, $TypeTable)
$Runspace.Open()
[System.Management.Automation.Runspaces.PSSession]::Create($Runspace, $TransportName, $null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment