Adding functions

Functions and other commands can be added to the InitialSessionState object in much the same way as variables. If a function is within a module, the module should be imported instead.

Functions, as SessionStateFunctionEntry objects, are added to the Commands property of the InitialSessionState object.

Simple functions can be added by defining the body of the function inline, as follows:

$functionEntry = [System.Management.Automation.Runspaces.SessionStateFunctionEntry]::new(
'Write-Greeting',
'Write-Host "Hello world"'
)

$initialSessionState.Commands.Add($functionEntry)

Functions may be added with scope options in the same way as is done with variables. Scoping is rarely used with functions.

If the function already exists in the current session, the output of Get-Command might be used to fill the SessionStateFunctionEntry object:

function Write-Greeting {
Write-Host 'Hello world'
}

$function = Get-Command Write-Greeting
$functionEntry = [System.Management.Automation.Runspaces.SessionStateFunctionEntry]::new(
$function.Name,
$function.Definition
)

$initialSessionState.Commands.Add($functionEntry)

Once the InitialSessionState object is filled with the required objects, it may be used to create a PowerShell instance or a RunspacePool.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.67.251