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?
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.
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 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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With