PowerShell WinForms阻止安装Windows功能

时间:2019-06-17 16:04:54

标签: winforms powershell xaml iis

我正在尝试通过PowerShell安装IIS功能,但无法这样做。如果我运行下面的代码,该脚本将挂起:

VERBOSE: Installation started... 
VERBOSE: Continue with installation?
VERBOSE: Prerequisite processing started...
WARNING: The plug-in for "Web Server (IIS)" is taking more time to load than expected

但是,如果我从控制台运行foreach循环,它就可以工作。这使我相信GUI中的某些内容已将其锁定。有人有什么想法吗?

# Checks to make sure you're running the script in admin mode since the script cannot complete otherwise.
# Bombs out if not otherwise. 
If ( !( [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
    ).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) ) {
    Write-Host "You are not running in an elevated window" -f Red
    Pause
    Exit
}


# loads .NET framework for the GUI.
[void][System.Reflection.Assembly]::LoadWithPartialName( 'presentationframework' )
[void][System.Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )


[xml]$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="SharePoint Deployment" Height="580" Width="400" >

<Grid Name="gridname" Background="#FF0070C9" Margin="0,0,0,0">

    <Label Name="SetupLabel" Content="SharePoint Deployment script" FontSize="13" HorizontalAlignment="Left" 
        VerticalAlignment="Top" Margin="30,20,0,0" Height="30" Width="200" Foreground="White" 
        FontWeight="Bold" />

    <Button Name="LoadIMG" Content="Load IMG File" HorizontalAlignment="Left" VerticalAlignment="Top" 
        Margin="255,22,0,0" Height="25" Width="100" />

    <Label Name="PreReq" Content="Pre-Req checks/installs" FontSize="11" HorizontalAlignment="Left" 
        VerticalAlignment="Top" Margin="30,65,0,0" Height="25" Width="320" Foreground="White" />
    <ProgressBar Name="PreReqProgressBar" HorizontalAlignment="Left" VerticalAlignment="Top" 
        Margin="30,95,0,0" Width="325" Height="25" />

    <Label Name="LogLabel" Content="Log..." HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="11"
        Margin="30,140,0,0" Height="25" Width="320" Foreground="White" />
    <RichTextBox Name="LogReport" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,170,0,0" 
        Height="340" Width="325" VerticalScrollBarVisibility="Auto" >
        <FlowDocument>
            <Paragraph>
                <Run Text=""/>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
</Grid>
</Window>
'@


# Attempts to render the xaml code.
$reader = New-Object System.Xml.XmlNodeReader $xaml

# Converts xaml into WPF raw format. Bombs out if there's a problem.
Try {
    $Form = [Windows.Markup.XamlReader]::Load( $reader )
}
Catch {
    Write-Warning "Unable to parse XML, with error: `n$( $Error[0] )
    `nHave you overwritten something? Drop your code into Visual Studio, it'll tell you where it's failing."

    Throw
}

# This line here creates variables for everything in the XAML code above where a name exists, and prefixes "form"
# in front.
# i.e. <Button Name="GoButton"... becomes $formgobutton. Use $formgobutton | get-member to see variables of 
# our newly created button. 
$xaml.SelectNodes( "//*[@Name]" ) | 
    ForEach-Object { Set-Variable -Name "form$( $_.Name )" -Value $Form.FindName( $_.Name ) }


Function Write-RichTextBox {

<#
.SYNOPSIS
    Makes changes to the fonts within the log box on a per amend basis.

.DESCRIPTION
    Makes changes to the fonts within the log box on a per amend basis.

.EXAMPLE
    Write-RichTextBox "Hello World" -colour Blue -Style Italic
    The $FormLogReport richtext box will update with "Hello World" in Blue italic font.

.NOTES
    $formLogReport.ScrollToEnd() will always place the scrollbar at the bottom of the richtext box when a 
    new line is added.
    $form.Dispatcher.Invoke( [Action]{},[Windows.Threading.DispatcherPriority]::ContextIdle ) updates the 
    richtext box on the fly. It's a TRY/CATCH as if the box is refreshed too quickly you'll get errors.
#>

Param(
    [string]$text,
    [string]$colour = "Black",
    [string]$style  = "Normal"
)

Begin {
    $RichTextRange = New-Object System.Windows.Documents.TextRange( 
        $formLogReport.Document.ContentEnd, $formLogReport.Document.ContentEnd )
}

Process {
    If ( $style -eq "Italic" ) {
        $RichTextRange.Text = "'$Text'"
    }
    else {
        $RichTextRange.Text = $Text
    }

    $RichTextRange.ApplyPropertyValue( ( [System.Windows.Documents.TextElement]::ForegroundProperty ), $colour )
    $RichTextRange.ApplyPropertyValue( ( [System.Windows.Documents.TextElement]::FontStyleProperty ), $style )
}

End {

    $formLogReport.ScrollToEnd()

    Try { 
    $form.Dispatcher.Invoke( [Action]{},[Windows.Threading.DispatcherPriority]::ContextIdle )
    }
    Catch { }
}
}


$windowsFeatures = ( "Web-Server", "Web-WebServer", "Web-Common-Http", "Web-Default-Doc", "Web-Static-Content",
    "Web-Dir-Browsing", "Web-Http-Errors", "Web-App-Dev", "Web-Asp-Net", "Web-Asp-Net45", "Web-Net-Ext", "Web-Net-Ext45", 
    "Web-ISAPI-Ext", "Web-ISAPI-Filter", "Web-Health", "Web-Http-Logging", "Web-Log-Libraries", "Web-Request-Monitor", 
    "Web-Http-Tracing", "Web-Security", "Web-Basic-Auth", "Web-Windows-Auth", "Web-Filtering", "Web-Performance", 
    "Web-Stat-Compression","Web-Dyn-Compression", "Web-Mgmt-Tools", "Web-Mgmt-Console", "WAS", "WAS-Process-Model", 
    "WAS-NET-Environment", "WAS-Config-APIs", "Windows-Identity-Foundation", "NET-HTTP-Activation", "NET-Non-HTTP-Activ", 
    "NET-WCF-Pipe-Activation45", "NET-WCF-HTTP-Activation45","Xps-Viewer" )



$formLoadIMG.Add_Click( {

    $formLogReport.Document.Blocks.Clear()
    Import-Module Servermanager

    Foreach ( $windowsFeature in $windowsFeatures ) {
        Try {
            $installwf = Install-WindowsFeature $windowsFeature -Confirm:$false -Restart:$false
            Write-RichTextBox "Successfully installed: "
            Write-RichTextBox $windowsFeature -style Italic
            Write-RichTextBox `r
        }
        Catch {
            Write-RichTextBox "Could not install $WindowsFeature" -colour Red
        }
    }

} )

$form.ShowDialog()

Google并没有提供太多帮助,因此非常感谢您提供一些反馈。谢谢

1 个答案:

答案 0 :(得分:0)

因此,感谢@RohinSidharth,您的评论支持了GUI引发问题的理论。

我构建了一个功能来“完成”工作,但这还不够,我仍然必须使用Invoke-Command才能使其正常工作。

Function InstallWinFeatures {


   $windowsFeatures = @( "Web-Server", "Web-WebServer", "Web-Common-Http", "Web-Default-Doc", "Web-Static-Content",
"Web-Dir-Browsing", "Web-Http-Errors", "Web-App-Dev", "Web-Asp-Net", "Web-Asp-Net45", "Web-Net-Ext", "Web-Net-Ext45", 
"Web-ISAPI-Ext", "Web-ISAPI-Filter", "Web-Health", "Web-Http-Logging", "Web-Log-Libraries", "Web-Request-Monitor", 
"Web-Http-Tracing", "Web-Security", "Web-Basic-Auth", "Web-Windows-Auth", "Web-Filtering", "Web-Performance", 
"Web-Stat-Compression","Web-Dyn-Compression", "Web-Mgmt-Tools", "Web-Mgmt-Console", "WAS", "WAS-Process-Model", 
"WAS-NET-Environment", "WAS-Config-APIs", "Windows-Identity-Foundation", "NET-HTTP-Activation", "NET-Non-HTTP-Activ", 
"NET-WCF-Pipe-Activation45", "NET-WCF-HTTP-Activation45","Xps-Viewer" )

foreach ( $Feature in $windowsFeatures ) {

    Try {
        Write-RichTextBox "trying to install $feature`r"
        Invoke-Command -ComputerName localhost -ScriptBlock { Install-WindowsFeature -Name $using:Feature -IncludeManagementTools } 
        Write-RichTextBox "Installed $feature`r"
    }
    Catch {
        Write-RichTextBox "Unable to remove $feature`r"
    }
}      
} 

如果有人知道为什么会发生这种情况,我将不知所措。 谢谢