从C#应用程序运行时,PowerShell脚本无法连接到计算机名

时间:2016-09-06 06:48:41

标签: c# powershell

当我从C#应用程序运行以下PowerShell脚本时,PowerShell脚本无法按名称连接到远程计算机。但它可以测试与IP地址的连接。当我在C#应用程序之外运行PowerShell代码时,它会起作用,并在C#应用程序中返回值“Offline”。任何人都可以帮我这个吗?

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.IO;

namespace ClientCheck
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private string RunScript(string scriptText)
        {
            // create Powershell runspace 
            InitialSessionState initial = InitialSessionState.CreateDefault();
            Runspace runspace = RunspaceFactory.CreateRunspace(initial);
            PowerShell ps = PowerShell.Create();
            ps.Runspace = runspace;
            //Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it 
            ps.Runspace.Open();
            ps.Runspace.SessionStateProxy.SetVariable("ComputerName", CompnameInput.Text);

            // create a pipeline and feed it the script text 
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script output objects into nicely formatted strings 
            // remove this line to get the actual objects that the script returns. For example, the script 
            // "Get-Process" returns a collection of System.Diagnostics.Process instances. 
            pipeline.Commands.Add("Out-String");

            // execute the script 
            Collection<PSObject> results = pipeline.Invoke();

            // close the runspace 
            ps.Runspace.Close();

            // convert the script result into a single string 
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            // return the results of the script that has 
            // now been converted to text 
            return stringBuilder.ToString();
        }
        // helper method that takes your script path, loads up the script 
        // into a variable, and passes the variable to the RunScript method 
        // that will then execute the contents 
        private string LoadScript(string filename)
        {
            try
            {
                // Create an instance of StreamReader to read from our file. 
                // The using statement also closes the StreamReader. 
                using (StreamReader sr = new StreamReader(filename))
                {

                    // use a string builder to get all our lines from the file 
                    StringBuilder fileContents = new StringBuilder();

                    // string to hold the current line 
                    string curLine;

                    // loop through our file and read each line into our 
                    // stringbuilder as we go along 
                    while ((curLine = sr.ReadLine()) != null)
                    {
                        // read each line and MAKE SURE YOU ADD BACK THE 
                        // LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF 
                        fileContents.Append(curLine + "\n");
                    }

                    // call RunScript and pass in our file contents 
                    // converted to a string 
                    return fileContents.ToString();
                }
            }
            catch (Exception e)
            {
                // Let the user know what went wrong. 
                string errorText = "The file could not be read:";
                errorText += e.Message + "\n";
                return errorText;
            }

        }

        private void Exitbutton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void DeviceStatusButton_Click(object sender, RoutedEventArgs e)
        {
            // run our script and put the result into our textbox 
            // NOTE: make sure to change the path to the correct location of your script
            Testlabel_Out.Content = RunScript(LoadScript(@"C:\VSProjects\ClientChecksNew\ClientChecksNew\Script\Get_Devicestatus.ps1"));
        }
    }
}

以下是PowerShell代码:

if (Test-Connection $computername -Quiet -Count 1) {
    $devicestatus = "Online"
} else {
    $devicestatus = "Offline"
}
$devicestatus

2 个答案:

答案 0 :(得分:0)

我似乎是我错误的XAML代码.. Compname_Input看起来像这样:

<TextBox x:Name="CompnameInput" HorizontalAlignment="Left" Height="18" Margin="242,14,0,0" TextWrapping="Wrap" Text="&#xD;&#xA;" VerticalAlignment="Top" Width="109" MaxLength="50" MaxLines="1" AutomationProperties.Name="CompNameinput" Tag="" Grid.Row="2"/>

不知道“Text =”是如何到达那里的,但那就是问题!

答案 1 :(得分:-1)

您必须在PowerShell脚本中添加-computername。

If(Test-Connection -computername $computername -Quiet -Count 1){
    $devicestatus = "Online"
}
Else{
    $devicestatus = "Offline"
}
$devicestatus