Skip to content

Instantly share code, notes, and snippets.

@FriedrichWeinmann
Created June 22, 2020 06:06
Show Gist options
  • Save FriedrichWeinmann/ac40c6d154d18989d6ce3f17cc50e6ba to your computer and use it in GitHub Desktop.
Save FriedrichWeinmann/ac40c6d154d18989d6ce3f17cc50e6ba to your computer and use it in GitHub Desktop.
Launches a target script in a new process, passing through all parameters.
function Start-Script {
<#
.SYNOPSIS
Launches a target script in a new process, passing through all parameters.
.DESCRIPTION
Launches a target script in a new process, passing through all parameters.
Uses dynamic parameters to offer the same signature as the script itself.
Uses the same powershell hosting application that executes Start-Script to start the new process.
.PARAMETER ScriptPath
Path to the scriptfile to launch.
.EXAMPLE
PS C:\> Start-Script .\newuser.ps1 -GivenName Max -Surname Mustermann
Launches the script "newuser.ps1" with the parameters passed through.
#>
[Alias('ss')]
[CmdletBinding()]
param (
[string]
$ScriptPath
)
DynamicParam {
$common = 'Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable'
if (($ScriptPath) -and (Test-Path $ScriptPath) -and (Get-Command $ScriptPath -ErrorAction Ignore))
{
$parameters = (Get-Command $ScriptPath).Parameters.Values | Where-Object Name -notin $common
$paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
foreach ($parameterObject in $parameters) {
$param = [System.Management.Automation.RuntimeDefinedParameter]::new($parameterObject.Name, $parameterObject.ParameterType, $parameterObject.Attributes)
$paramDictionary.Add($parameterObject.Name, $param)
}
return $paramDictionary
}
}
process {
$stringParams = $PSBoundParameters | ConvertTo-PSFHashtable -Exclude ScriptPath | ConvertTo-PSFClixml
$code = {
$path = '{0}'
$parameters = '{1}' | ConvertFrom-PSFClixml
& $path @parameters
}.ToString() -f $ScriptPath, $stringParams
$encodedCommand = [convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($code))
$powershell = (Get-Process -Id $pid).Path
Start-Process -FilePath $powershell -ArgumentList '-NoExit','-NoProfile', '-EncodedCommand', $encodedCommand
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment