![](/img/trans.png)
[英]PowerShell script acts different when run from C# application then from PowerShell ISE
[英]PowerShell script can't connect to computername when run from C# application
當我從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
我似乎是我的XAML代碼錯了。Compname_Input看起來像這樣:
<TextBox x:Name="CompnameInput" HorizontalAlignment="Left" Height="18" Margin="242,14,0,0" TextWrapping="Wrap" Text="
" VerticalAlignment="Top" Width="109" MaxLength="50" MaxLines="1" AutomationProperties.Name="CompNameinput" Tag="" Grid.Row="2"/>
不知道“ Text =”如何到達那里,但這就是問題所在!
您必須將-computername添加到您的Powershell腳本中。
If(Test-Connection -computername $computername -Quiet -Count 1){
$devicestatus = "Online"
}
Else{
$devicestatus = "Offline"
}
$devicestatus
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.