我想通过 powershell 安装一些功能。即使它没有安装任何功能也会PSObject
返回。Installed
环境:Windows Server 2019 x64,应用:.NET Framework + PowerShellStandard.Library 5.1
应用程序是为 x64 构建的以运行ServerManager
模块。
安装功能的代码,例如管理控制台
InstallWindowsFeature(powerShell, "Web-Mgmt-Console");
安装功能
void InstallWindowsFeature(PowerShell powerShell, string featureName)
{
if(IsWindowsFeatureInstalled(powerShell, featureName)) // Get-WindowsFeature call..
{
Console.WriteLine($"{featureName} is already installed. Skipping install...");
return;
}
powerShell.AddCommand("Install-WindowsFeature");
powerShell.AddParameter("Name", featureName);
Collection<PSObject> psObjects = powerShell.Invoke();
foreach (dynamic psObject in psObjects.Where(x => x != null))
Console.WriteLine($"Result: Success - {psObject.Success}, Restart needed: {psObject.RestartNeeded}, Exit code: {psObject.ExitCode}");
}
PowerShell 初始化
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ImportPSModule(new string[] { "ServerManager" });
Runspace powerShellRunscape = RunspaceFactory.CreateRunspace(initialSessionState);
powerShellRunscape.Open();
PowerShell powerShell = PowerShell.Create();
powerShell.Runspace = powerShellRunscape;
// install call
powerShell.Dispose();
powerShellRunscape.Close();
如何正确运行 Install-WindowsFeature?