C#调用powershell“ Get-Website”总是返回空

问题描述 投票:0回答:1

我正在尝试使用Powershell从C#中读取IIS本地网站但是我总是得到一个空的输出

public static ManageWebsite GetWebSiteStatus(string websiteName)
{

    ManageWebsite websiteState = new ManageWebsite();
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();

    PowerShell ps = PowerShell.Create(); // Create a new PowerShell instance
    ps.Runspace = runspace; // Add the instance to the runspace
    ps.Commands.AddScript(@"Get-Website -Name """ + websiteName + @""" | %{$_.state}"); // Add a script

    Collection<PSObject> results = ps.Invoke();
    string powershell_output = string.Empty;

    runspace.Close();

    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        powershell_output = obj.BaseObject.ToString();

    }

    websiteState.Status = powershell_output;
    websiteState.WebSite = websiteName;
    return websiteState;
}

我不知道为什么,我总是使用该函数在C#中使用powershell调用其他东西,并且总是可以正常工作

c# asp.net powershell iis web-testing
1个回答
0
投票
您将变量设置为空字符串,可以,但是每次遍历对象时都将其覆盖。如果您从未得到对象,它仍然是一个空字符串!然后您将其分配给Status websiteState.Status。

string powershell_output = string.Empty; foreach (PSObject obj in results) { powershell_output = obj.BaseObject.ToString(); } websiteState.Status = powershell_output;

因此,如果您的websiteName从未从Get-Website获得结果,则将始终有一个未设置预期属性的对象。如果从Get-Website获得结果,则只能从最后一个迭代对象中获取一些东西,形式是BaseObject.ToString()。在尝试分配值之前,您可能需要再检查一下是否还可以得到一些东西。

© www.soinside.com 2019 - 2024. All rights reserved.