Last active
October 17, 2018 11:21
-
-
Save KirkMunro/9288214d59a89b965974852eb985eff5 to your computer and use it in GitHub Desktop.
Invoking multiple PowerShell commands one at a time from C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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