为什么我不能在C#中使用我的自定义Powershell模块

时间:2014-06-30 20:13:28

标签: c# powershell

我正在Visual Studio 2010中编写一个小GUI,用于我为windows powershell制作的一个自定义模块,但不幸的是,我可以使用的唯一模块是默认模块(例如ActiveDirectory)。

这是应该运行的代码,但它什么都不做!我有一些代码成功运行,但我无法发布,因为它有敏感的信息。

请帮帮我,这让我想退出并成为Macintosh管理员

    private void getStateOfSelectedLab(object sender, EventArgs e)
    {
        stateBox.Items.Clear();

        stateBox.Items.Add("Please Wait (This may take a few minutes)...");

        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            PowerShellInstance.AddScript("import-module ActiveDirectory");  //import modules
            PowerShellInstance.Invoke();    //executes command pipeline

            PowerShellInstance.AddScript("import-module LANModule");
            PowerShellInstance.Invoke();

            PowerShellInstance.AddScript("Get-LabState " + selectLab.SelectedItem.ToString());
            //PowerShellInstance.AddParameter("lab", selectLab.SelectedItem.ToString());

            Collection<PSObject> theState = PowerShellInstance.Invoke();

            string[] stateOfLab = new string[theState.Count];

            int i = 0;

            foreach (PSObject result in theState)
            {
                string aResult = result.ToString();

                stateOfLab[i] = aResult;
                i++;
            }

            stateBox.Items.Clear();

            //stateBox.Items.Add(theState.Count);

            stateBox.Items.AddRange(stateOfLab);
        }
    }

这是有效的脚本:

        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            PowerShellInstance.AddScript("import-module ActiveDirectory");  //import modules
            PowerShellInstance.Invoke();    //executes command pipeline

            PowerShellInstance.AddScript("import-module LANModule");
            PowerShellInstance.Invoke();

            //add another to the pipe, this one grabs all labs
            PowerShellInstance.AddScript("$OU = [REDACTED]");
            PowerShellInstance.AddScript("Get-ADOrganizationalUnit -Filter * -SearchBase $OU | sort-object");

            //returned collection of labs
            Collection<PSObject> allLabs = PowerShellInstance.Invoke();

            foreach (PSObject lab in allLabs)
            {
                string[] toks = lab.ToString().Split(',');
                string labName = toks[0].Substring(3);
                selectLab.Items.Add(labName);
            }
        }
    }

0 个答案:

没有答案