Quick question regarding Powershell invokes within C#
I'd like to be able to ask C# to load a powershell module in a separate method, then run Powershell commands in another method.
Currently from my (limited) knowledge of invoking PS in C#, it looks like I cant access the powershell instance from another method - is this correct?
Code example below. I'm looking into usind runspaces, but did not want to burn too much time researching this either.
Any help in best way to access a powershell instance (with module loaded) from other methods within a class would be really appreciated.
namespace Test
{
public class Test
{
public void loadModule()
{
using (PowerShell PowershellInstance = PowerShell.Create())
{
PowershellInstance.AddScript("Add-PSSnapin VMware.VimAutomation.Core");
PowershellInstance.Invoke();
if (PowershellInstance.Streams.Error.Count > 0)
{
infoBox.Text = "Error loading snapin";
return;
}
else
{
infoBox.Text = "Loaded";
}
PowershellInstance.Commands.Clear();
}
}
public void someOtherMethod()
{
//do some more powershell - without loading module
}
Depending on how you implemented this with a class variable, you'll probably also want to implement IDisposable to cleanup your PowerShell reference. Otherwise you won't free up all memory\\resources properly.
Something like this:
public class Test : IDisposable
{
private bool disposed;
private PowerShell ps;
public Test()
{
disposed = false;
ps = PowerShell.Create();
}
public void loadModule()
{
ps.AddCommand("Add-PSSnapin")
.AddParameter("Name", "VMware.VimAutomation.Core")
.Invoke();
if (ps.HadErrors)
infoBox.Text = "Error loading snapin";
else
infoBox.Text = "Loaded";
ps.Commands.Clear();
}
public void someOtherMethod()
{
//do some more powershell - without loading module
ps.Commands.Clear();
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (!disposed)
{
disposed = true;
if (disposing)
{
if (ps != null)
{
ps.Dispose();
ps = null;
}
}
}
}
}
Note that you can use ps.HadErrors instead of checking the errors stream.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.