Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing PowerShell module in C#

I'm trying to write some C# code to interact with Lync using PowerShell, and I need to import the Lync module before executing the Lync cmdlets. However, my code doesn't seem to import the module and I keep getting a "get-csuser command not found" exception. Here is my code:

PowerShell ps = PowerShell.Create();
ps.AddScript(@"import-module Lync");
ps.Invoke();
ps.Commands.AddCommand("Get-csuser");
foreach (PSObject result in ps.Invoke())
{
    Console.WriteLine(result.Members["Name"].Value);
}

Any idea how can I import the Lync module?

like image 689
NullPointer Avatar asked Jun 12 '13 16:06

NullPointer


People also ask

How do I import a PowerShell module?

To import the module into all sessions, add an Import-Module command to your PowerShell profile. To manage remote Windows computers that have PowerShell and PowerShell remoting enabled, create a PSSession on the remote computer and then use Get-Module -PSSession to get the PowerShell modules in the PSSession.

Can I copy PowerShell module to another computer?

Find the modules you want to transfer and copy all Modules folders to the new machine in the same folder “C:\Program Files\WindowsPowerShell\Modules”. In this example all folders started with VMware. When the copy process has finished close all powershell instances at the “offline” PC and reopen it.

How do I use PowerShell modules?

How to Import a Module into Every Session. The Import-Module command imports modules into your current PowerShell session. To import a module into every PowerShell session that you start, add the Import-Module command to your PowerShell profile. For more information about profiles, see about_Profiles.


1 Answers

Got it, the module needs to be imported by its full path, and also the execution policy for both 64-bit powershell and 32-bit powershell need to be set to Unrestricted (or anything other than restricted depending on your case). Here's the code:

static void Main(string[] args)
{
    InitialSessionState initial = InitialSessionState.CreateDefault();
    initial.ImportPSModule(new string[] {"C:\\Program Files\\Common Files\\Microsoft Lync Server 2010\\Modules\\Lync\\Lync.psd1"} );
    Runspace runspace = RunspaceFactory.CreateRunspace(initial);
    runspace.Open();     
    PowerShell ps = PowerShell.Create();
    ps.Runspace = runspace;
    ps.Commands.AddCommand("Get-csuser");

    foreach (PSObject result in ps.Invoke())
    {
        Console.WriteLine(result.Members["Identity"].Value);
    }
}
like image 188
NullPointer Avatar answered Oct 06 '22 19:10

NullPointer