Skip to content

Instantly share code, notes, and snippets.

@KirkMunro
Last active October 17, 2018 11:21
Show Gist options
  • Save KirkMunro/9288214d59a89b965974852eb985eff5 to your computer and use it in GitHub Desktop.
Save KirkMunro/9288214d59a89b965974852eb985eff5 to your computer and use it in GitHub Desktop.
Invoking multiple PowerShell commands one at a time from C#
var sessionState = InitialSessionState.CreateDefault();
sessionState.ImportPSModule(new string[] { "AzureRM.Profile" });
using (var psRunspace = RunspaceFactory.CreateRunspace(sessionState))
{
using (var ps = PowerShell.Create())
{
// This is not intuitive and an unnecessary annoyance
ps.Runspace = psRunspace;
ps.AddCommand("Connect-AzureRmAccount")
.AddParameter("ServicePrincipal")
.AddParameter("TenantId", tenantName)
.AddParameter("Subscription", subscriptionId)
.AddParameter("Credential", credential);
var results = ps.Invoke();
// Process results
}
// Additional code here
using (var ps = PowerShell.Create())
{
// Again, not intuitive, easily forgotten
ps.Runspace = psRunspace;
ps.AddCommand("Get-AzureRMVM")
.AddParameter("ResourceGroupName", resourceGroupName)
.AddParameter("Name", vmName);
var results = ps.Invoke();
// Work with VM
}
}
var sessionState = InitialSessionState.CreateDefault();
sessionState.ImportPSModule(new string[] { "AzureRM.Profile" });
using (var psRunspace = RunspaceFactory.CreateRunspace(sessionState))
{
// This is much more expressive - create a new PS instance in the runspace provided.
// It also helps raise visibility that you can use this model (which is necessary
// if you want to invoke multiple PS commands one at a time from a non PS .NET assembly).
using (var ps = PowerShell.Create(psRunspace))
{
ps.AddCommand("Connect-AzureRmAccount")
.AddParameter("ServicePrincipal")
.AddParameter("TenantId", tenantName)
.AddParameter("Subscription", subscriptionId)
.AddParameter("Credential", credential);
var results = ps.Invoke();
// Process results
}
// Additional code here
// Much more elegant and clear what is being done at a glance
using (var ps = PowerShell.Create(psRunspace))
{
ps.AddCommand("Get-AzureRMVM")
.AddParameter("ResourceGroupName", resourceGroupName)
.AddParameter("Name", vmName);
var results = ps.Invoke();
// Work with VM
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment