Add S.M.A.PowerShell.Create method overload with Runspace argument (#8057)

This commit is contained in:
Kirk Munro
2019-01-07 11:04:42 -08:00
committed by Aditya Patwardhan
parent b8f9532b41
commit 23f6e8ff40
2 changed files with 45 additions and 5 deletions
@@ -4,16 +4,17 @@
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; // for fxcop.
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using System.Diagnostics.CodeAnalysis; // for fxcop.
using Dbg = System.Management.Automation.Diagnostics;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
@@ -864,6 +865,32 @@ namespace System.Management.Automation
return result;
}
/// <summary>
/// Constructs an empty PowerShell instance and associates it with the provided
/// Runspace; a script or command must be added before invoking this instance.
/// </summary>
/// <param name="runspace">Runspace in which to invoke commands.</param>
/// <returns>An instance of PowerShell.</returns>
/// <remarks>
/// The required Runspace argument is accepted no matter what state it is in.
/// Leaving Runspace state management to the caller allows them to open their
/// runspace in whatever manner is most appropriate for their application
/// (in another thread while this instance of the PowerShell class is being
/// instantiated, for example).
/// </remarks>
public static PowerShell Create(Runspace runspace)
{
if (runspace == null)
{
throw new PSArgumentNullException(nameof(runspace));
}
PowerShell result = Create();
result.Runspace = runspace;
return result;
}
/// <summary>
/// Creates a nested powershell within the current instance.
/// Nested PowerShell is used to do simple operations like checking state
@@ -6,6 +6,19 @@ Describe 'Basic engine APIs' -Tags "CI" {
[powershell]::Create() | Should -Not -BeNullOrEmpty
}
It 'can create instance with runspace' {
$rs = [runspacefactory]::CreateRunspace()
$ps = [powershell]::Create($rs)
$ps | Should -Not -BeNullOrEmpty
$ps.Runspace | Should -Be $rs
$ps.Dispose()
$rs.Dispose()
}
It 'cannot create instance with null runspace' {
{ [powershell]::Create([runspace]$null) } | Should -Throw -ErrorId 'PSArgumentNullException'
}
It "can load the default snapin 'Microsoft.WSMan.Management'" -skip:(-not $IsWindows) {
$ps = [powershell]::Create()
$ps.AddScript("Get-Command -Name Test-WSMan") > $null