Advertisement
Guest User

WPF-XAML-in-Powershell

a guest
Sep 1st, 2016
533
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $Global:syncHash = [hashtable]::Synchronized(@{})
  2. $newRunspace =[runspacefactory]::CreateRunspace()
  3. $newRunspace.ApartmentState = "STA"
  4. $newRunspace.ThreadOptions = "ReuseThread"
  5. $newRunspace.Open()
  6. $newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
  7. # Load WPF assembly if necessary
  8. [void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
  9. $psCmd = [PowerShell]::Create().AddScript({
  10. $inputXML = @"
  11. <Window
  12.        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  13.        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  14.        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  15.        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  16.        xmlns:local="clr-namespace:WpfApplication1;assembly=WpfApplication1"
  17.        mc:Ignorable="d"
  18.        Title="MGI Utility Tools Windows" Height="380.801" Width="647.356">
  19.    <Grid Margin="0,0,-8,-66">
  20.        <Grid.RowDefinitions>
  21.            <RowDefinition/>
  22.        </Grid.RowDefinitions>
  23.        <Button x:Name="Run_Script_btn" Content="Run Script" HorizontalAlignment="Left" Margin="28,306,0,0" VerticalAlignment="Top" Width="75"/>
  24.        <TextBox x:Name="filename_txtbox" HorizontalAlignment="Left" Height="28" Text="$env:computername" Margin="101,70,0,0" VerticalAlignment="Top" Width="116"/>
  25.        <Button x:Name="browse_btn" Content="Browse" HorizontalAlignment="Left" Height="28" Margin="224,69,0,0" VerticalAlignment="Top" Width="52" IsEnabled="False"/>
  26.        <TextBlock x:Name="Caption_txtBlock" HorizontalAlignment="Left" Height="28" Margin="10,70,0,0" TextWrapping="Wrap" Text="Server Name" VerticalAlignment="Top" Width="84" FontSize="14" TextAlignment="Right"/>
  27.        <RadioButton x:Name="server_rbtn" Content="Server Name" HorizontalAlignment="Left" Margin="41,109,0,0" VerticalAlignment="Top" IsChecked="True"/>
  28.        <RadioButton x:Name="File_rbtn" Content="File" HorizontalAlignment="Left" Margin="176,109,0,0" VerticalAlignment="Top" IsChecked="False"/>
  29.        <ProgressBar x:Name="progress_bar" HorizontalAlignment="Left" Height="30" Margin="28,249,0,0" VerticalAlignment="Top" Width="235"/>
  30.        <Button x:Name="Exit_btn" Content="Exit" HorizontalAlignment="Left" Margin="188,306,0,0" VerticalAlignment="Top" Width="75"/>
  31.        <GroupBox x:Name="groupBox_radiobtn" Header="Select Tools" HorizontalAlignment="Left" Height="101" Margin="28,135,0,0" VerticalAlignment="Top" Width="114">
  32.            <Grid HorizontalAlignment="Left" Height="101" VerticalAlignment="Top"
  33.           Width="104" Margin="0,0,-2,-22">
  34.                <RadioButton x:Name="Uptime_rbtn" Content="Uptime" HorizontalAlignment="Left" Margin="5,3,0,0" VerticalAlignment="Top" IsChecked="True"/>
  35.                <RadioButton x:Name="Diskspc_rbtn" Content="Disk Space" HorizontalAlignment="Left" Margin="5,23,0,0" VerticalAlignment="Top" IsChecked="False"/>
  36.                <RadioButton x:Name="DiskCln_rbtn" Content="Disk Cleanup" HorizontalAlignment="Left" Margin="5,43,0,0" VerticalAlignment="Top" IsChecked="False"/>
  37.                <RadioButton x:Name="Inventory_rbtn" Content="Inventory" HorizontalAlignment="Left" Margin="5,63,0,0" VerticalAlignment="Top" IsChecked="False"/>
  38.            </Grid>
  39.        </GroupBox>
  40.        <GroupBox x:Name="groupBox_invoption" Header="Inventory Option" Height="74" Margin="147,137,384,0" VerticalAlignment="Top" IsEnabled="False">
  41.            <Grid HorizontalAlignment="Left" Height="91" VerticalAlignment="Top"
  42.           Width="104" Margin="0,0,-2,-12">
  43.                <RadioButton x:Name="inventory_HW" Content="Hardware" HorizontalAlignment="Left" IsChecked="False" Margin="5,5,0,0" VerticalAlignment="Top"/>
  44.                <RadioButton x:Name="inventory_SW" Content="Software" HorizontalAlignment="Left" IsChecked="False" Margin="5,25,0,0" VerticalAlignment="Top"/>
  45.            </Grid>
  46.        </GroupBox>
  47.        <Image x:Name="image" HorizontalAlignment="Center" Height="60" Margin="0,4,0,0" VerticalAlignment="Top" Width="288" Source="$scriptPath\image.png"/>
  48.        <TextBox x:Name="out_textBox" HorizontalAlignment="Left" Height="318" Margin="299,10,0,0" Text="Someting" TextWrapping="Wrap" VerticalAlignment="Top" Width="323" Background="Black" Foreground="Cyan"/>
  49.    </Grid>
  50. </Window>
  51. "@      
  52.  
  53. $inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^<Win.*', '<Window'
  54.  
  55. [void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
  56. [xml]$XAML = $inputXML
  57. #Read XAML
  58.  
  59.     $reader=(New-Object System.Xml.XmlNodeReader $xaml)
  60.    
  61.     $syncHash.Window=[Windows.Markup.XamlReader]::Load( $reader )
  62.  
  63.     [xml]$XAML = $xaml
  64.         $xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
  65.         #Find all of the form types and add them as members to the synchash
  66.         $syncHash.Add($_.Name,$syncHash.Window.FindName($_.Name) ) }
  67.  
  68.  
  69.     $Script:JobCleanup = [hashtable]::Synchronized(@{})
  70.     $Script:Jobs = [system.collections.arraylist]::Synchronized((New-Object System.Collections.ArrayList))
  71.  
  72.     #region Background runspace to clean up jobs
  73.     $jobCleanup.Flag = $True
  74.     $newRunspace =[runspacefactory]::CreateRunspace()
  75.     $newRunspace.ApartmentState = "STA"
  76.     $newRunspace.ThreadOptions = "ReuseThread"          
  77.     $newRunspace.Open()        
  78.     $newRunspace.SessionStateProxy.SetVariable("jobCleanup",$jobCleanup)    
  79.     $newRunspace.SessionStateProxy.SetVariable("jobs",$jobs)
  80.     $jobCleanup.PowerShell = [PowerShell]::Create().AddScript({
  81.         #Routine to handle completed runspaces
  82.         Do {    
  83.             Foreach($runspace in $jobs) {            
  84.                 If ($runspace.Runspace.isCompleted) {
  85.                     [void]$runspace.powershell.EndInvoke($runspace.Runspace)
  86.                     $runspace.powershell.dispose()
  87.                     $runspace.Runspace = $null
  88.                     $runspace.powershell = $null              
  89.                 }
  90.             }
  91.             #Clean out unused runspace jobs
  92.             $temphash = $jobs.clone()
  93.             $temphash | Where {
  94.                 $_.runspace -eq $Null
  95.             } | ForEach {
  96.                 $jobs.remove($_)
  97.             }        
  98.             Start-Sleep -Seconds 1    
  99.         } while ($jobCleanup.Flag)
  100.     })
  101.     $jobCleanup.PowerShell.Runspace = $newRunspace
  102.     $jobCleanup.Thread = $jobCleanup.PowerShell.BeginInvoke()  
  103.     #endregion Background runspace to clean up jobs
  104.    
  105.    
  106.     #region Flie browser
  107.     Function fe-ne ($fd){
  108.  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Win32.OpenFileDialog") | Out-Null
  109.  $opf = New-Object Microsoft.Win32.OpenFileDialog
  110.  $opf.initialDirectory = "$fd"
  111.  $opf.filter = "Server Name files (*.Txt)|*.Txt"
  112.  $opf.ShowDialog() | Out-Null
  113.  $opf.filename
  114.  $synchash.filename_txtbox.Text = $opf.filename
  115.  }
  116.     $syncHash.browse_btn.add_click({fe-ne})
  117.     #endregion Flie browser
  118.  
  119.     #region Single server and multiple server text file selection
  120.    
  121.     $synchash.File_rbtn.add_click({
  122.     $syncHash.Caption_txtBlock.Text = "File Name"
  123.     $syncHash.browse_btn.IsEnabled = $True
  124.     $synchash.filename_txtbox.Text = ""
  125.     })
  126.  
  127.     $synchash.server_rbtn.add_click({
  128.     $syncHash.Caption_txtBlock.Text = "Server Name"
  129.     $syncHash.browse_btn.IsEnabled = $false
  130.     $synchash.filename_txtbox.Text = ""
  131.     })
  132.  
  133.     #endregion Single server and multiple server text file selection
  134.  
  135.     #region radio button controls
  136.     $synchash.Uptime_rbtn.add_click({$synchash.inventory_HW.Ischecked = $false; $synchash.inventory_SW.Ischecked = $false; $synchash.groupBox_invoption.IsEnabled = $false})
  137.     $syncHash.DiskCln_rbtn.add_click({$synchash.inventory_HW.Ischecked = $false; $synchash.inventory_SW.Ischecked = $false; $synchash.groupBox_invoption.IsEnabled = $false})
  138.     $synchash.Diskspc_rbtn.add_click({$synchash.inventory_HW.Ischecked = $false; $synchash.inventory_SW.Ischecked = $false; $synchash.groupBox_invoption.IsEnabled = $false})
  139.     $syncHash.Inventory_rbtn.add_click({$synchash.inventory_HW.Ischecked = $true;$synchash.groupBox_invoption.IsEnabled = $true})
  140.     #endregion radio button controls
  141.  
  142.    
  143.     #region run button
  144.     $synchash.Run_Script_btn.add_click(
  145.    
  146.     {              
  147.         #region Boe's Additions
  148.         $newRunspace =[runspacefactory]::CreateRunspace()
  149.         $newRunspace.ApartmentState = "STA"
  150.         $newRunspace.ThreadOptions = "ReuseThread"          
  151.         $newRunspace.Open()
  152.         $newRunspace.SessionStateProxy.SetVariable("SyncHash",$SyncHash)
  153.         $PowerShell = [PowerShell]::Create().AddScript({
  154. Function Update-Window {
  155.         Param (
  156.             $Control,
  157.             $Property,
  158.             $Value,
  159.             [switch]$AppendContent
  160.         )
  161.  
  162.         # This is kind of a hack, there may be a better way to do this
  163.         If ($Property -eq "Close") {
  164.             $syncHash.Window.Dispatcher.invoke([action]{$syncHash.Window.Close()},"Normal")
  165.             Return
  166.         }
  167.  
  168.         # This updates the control based on the parameters passed to the function
  169.         $syncHash.$Control.Dispatcher.Invoke([action]{
  170.             # This bit is only really meaningful for the TextBox control, which might be useful for logging progress steps
  171.             If ($PSBoundParameters['AppendContent']) {
  172.                 $syncHash.$Control.AppendText($Value)
  173.             } Else {
  174.                 $syncHash.$Control.$Property = $Value
  175.             }
  176.         }, "Normal")
  177.     }
  178. Function out-CSV {
  179. [CmdletBinding(DefaultParameterSetName='Delimiter',
  180.   SupportsShouldProcess=$true, ConfirmImpact='Medium')]
  181. param(
  182.  [Parameter(Mandatory=$true, ValueFromPipeline=$true,
  183.            ValueFromPipelineByPropertyName=$true)]
  184.  [System.Management.Automation.PSObject]
  185.  ${InputObject},
  186.  [Parameter(Mandatory=$true, Position=0)]
  187.  [Alias('PSPath')]
  188.  [System.String]
  189.  ${Path},
  190.  [Switch]
  191.  ${Append},
  192.  [Switch]
  193.  ${Force},
  194.  [Switch]
  195.  ${NoClobber},
  196.  [ValidateSet('Unicode','UTF7','UTF8','ASCII','UTF32',
  197.                   'BigEndianUnicode','Default','OEM')]
  198.                  
  199.  [System.String]
  200.  ${Encoding},
  201.  [Parameter(ParameterSetName='Delimiter', Position=1)]
  202.  [ValidateNotNull()]
  203.  [System.Char]
  204.  ${Delimiter},
  205.  [Parameter(ParameterSetName='UseCulture')]
  206.  [Switch]
  207.  ${UseCulture},
  208.  [Alias('NTI')]
  209.  [Switch]
  210.  ${NoTypeInformation})
  211. begin
  212. {
  213.  $AppendMode = $false
  214.  try {
  215.   $outBuffer = $null
  216.   if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
  217.   {
  218.       $PSBoundParameters['OutBuffer'] = 1
  219.   }
  220.   $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Export-Csv',
  221.     [System.Management.Automation.CommandTypes]::Cmdlet)
  222.  $scriptCmdPipeline = ''
  223.  if ($Append) {  
  224.   $PSBoundParameters.Remove('Append') | Out-Null    
  225.   if ($Path) {
  226.    if (Test-Path $Path) {
  227.     $AppendMode = $true
  228.     if ($Encoding.Length -eq 0) {
  229.      $Encoding = 'ASCII'
  230.     }
  231.     $scriptCmdPipeline += 'ConvertTo-Csv -NoTypeInformation '
  232.      if ( $UseCulture ) {
  233.      $scriptCmdPipeline += ' -UseCulture '
  234.     }
  235.     if ( $Delimiter ) {
  236.      $scriptCmdPipeline += " -Delimiter '$Delimiter' "
  237.     }
  238.     $scriptCmdPipeline += ' | Foreach-Object {$start=$true}'
  239.     $scriptCmdPipeline += '{if ($start) {$start=$false} else {$_}} '
  240.    
  241.     # Add file output
  242.     $scriptCmdPipeline += " | Out-File -FilePath '$Path'"
  243.     $scriptCmdPipeline += " -Encoding '$Encoding' -Append "
  244.         if ($Force) {
  245.      $scriptCmdPipeline += ' -Force'
  246.     }
  247.         if ($NoClobber) {
  248.      $scriptCmdPipeline += ' -NoClobber'
  249.     }      }  } }  
  250.  $scriptCmd = {& $wrappedCmd @PSBoundParameters }
  251.  if ( $AppendMode ) {  $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
  252.       $scriptCmdPipeline
  253.     ) }
  254.   else {  $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
  255.       [string]$scriptCmd    ) }
  256.  $steppablePipeline = $scriptCmd.GetSteppablePipeline(
  257.         $myInvocation.CommandOrigin)
  258.  $steppablePipeline.Begin($PSCmdlet)
  259.  } catch {   throw }}
  260. process
  261. {
  262.   try {      $steppablePipeline.Process($_)  } catch {      throw  }
  263. }
  264. end
  265. {
  266.   try {      $steppablePipeline.End()  } catch {      throw  }}
  267. }  
  268. $msgbx = New-Object -ComObject Wscript.Shell -ErrorAction Stop
  269. Function Get-UPTime{
  270.  
  271.    [CmdletBinding(SupportsShouldProcess=$true,
  272.                   ConfirmImpact='Medium')]
  273.     Param
  274.     (
  275.         [Parameter(
  276.                    Position=0,
  277.                    ValueFromPipeline=$true,
  278.                    ValueFromPipelineByPropertyName=$true)]
  279.         [String]$ErrorLog =  "c:\tmp\UptimeError.txt",
  280.         [String]$OutputFile = "c:\tmp\Uptimeoutput.csv",
  281.         [String]$date = (Get-Date)  
  282.      )
  283.  
  284.  
  285.     Begin
  286.     {
  287.    
  288.     }
  289.     Process
  290.     {
  291.            
  292.            try {
  293.            if ( Test-Connection -ComputerName $server -Count 1 -ErrorAction stop) {
  294.                             #Write-Verbose $Server
  295.                             if ($server -like "*dmz*")
  296.                             {$wmi = gwmi -class Win32_OperatingSystem -computer $server -Credential $cred -ea stop -ErrorVariable $CError }
  297.  
  298.                             else {$wmi = gwmi -class Win32_OperatingSystem -computer $server -ea stop -ErrorVariable $CError}
  299.                            
  300.                             $LBTime = $wmi.ConvertToDateTime($wmi.Lastbootuptime)
  301.                             [TimeSpan]$uptime = New-TimeSpan $LBTime $(get-date)
  302.                                                                        
  303.                             $outupt = New-Object -TypeName psobject -Property @{"ComputerName" = $server
  304.                              "Uptime" = "$($uptime.days) Days $($uptime.hours) Hours $($uptime.minutes) Minutes $($uptime.seconds) Seconds"
  305.                              }
  306.                             if ($synchash.File_rbtn.IsChecked -eq $true){
  307.                            $outupt | select ComputerName, uptime | out-Csv -Path $OutputFile -Append -NoTypeInformation  } else{                               
  308.                         $msgbx.Popup("$($uptime.days) Days $($uptime.hours) Hours $($uptime.minutes) Minutes $($uptime.seconds) Seconds",0,"Uptime for $Server",48+0)}
  309.                         }
  310.            
  311.                 }
  312.                 catch
  313.                 {#Write-Verbose "Failed processing $Server"
  314.                 $Server | Out-File $ErrorLog -Append
  315.                 }
  316.                 update-window -Control Progress_Bar -Property Value -Value "$synchash.progress_bar.Value+1"
  317.                
  318.        
  319.                
  320.            
  321.  
  322.     }
  323.     End
  324.     {
  325.     if ($synchash.progress_bar.Value -eq $synchash.progress_bar.Maximum){update-window -Control Progress_Bar -Property Foreground -Value 'Green'}
  326.     }
  327. }
  328.          # update-window -Control Progress_Bar -Property Value -Value 25
  329. if($SyncHash.File_rbtn.IsChecked -eq $True){$servers = gc $SyncHash.filename_txtbox.Text}else{$servers = $SyncHash.filename_txtbox.Text}
  330. foreach($server in $servers){Get-UPTime}
  331.  
  332. <#                        
  333. Update-Window -Control StarttextBlock -Property ForeGround -Value White                                                      
  334. start-sleep -Milliseconds 850
  335. update-window -Control Progress_Bar -Property Value -Value 25
  336. update-window -Control TextBox -property text -value $x -AppendContent
  337. Update-Window -Control ProcesstextBlock -Property ForeGround -Value White                                                      
  338. start-sleep -Milliseconds 850
  339. update-window -Control ProgressBar -Property Value -Value 50
  340. Update-Window -Control FiltertextBlock -Property ForeGround -Value White                                                      
  341. start-sleep -Milliseconds 500
  342. update-window -Control ProgressBar -Property Value -Value 75
  343. Update-Window -Control DonetextBlock -Property ForeGround -Value White                                                      
  344. start-sleep -Milliseconds 200
  345. update-window -Control ProgressBar -Property Value -Value 100
  346. #>
  347.         })
  348.         $PowerShell.Runspace = $newRunspace
  349.         [void]$Jobs.Add((
  350.             [pscustomobject]@{
  351.                 PowerShell = $PowerShell
  352.                 Runspace = $PowerShell.BeginInvoke()
  353.             }
  354.         ))
  355.     }
  356.  
  357.     )
  358.  
  359.     #endregion run button
  360.  
  361.  
  362.     #region Drag n Drop Control
  363.     $syncHash.Window.AllowDrop = $true
  364.  
  365.     $syncHash.Window.add_drop({$1 = $_.Data.GetFileDropList()
  366.     if($1 -like "*.txt"){$syncHash.filename_txtbox.Text = $1
  367.     $syncHash.File_rbtn.IsChecked = $True
  368.     $synchash.Caption_txtBlock.Text = "File Name"
  369.     $syncHash.browse_btn.IsEnabled = $True}
  370.     })
  371.  
  372.     #endregion Drag n Drop Control
  373.    
  374.     #region Window Close
  375.    
  376.     $syncHash.Exit_btn.add_click({
  377.     $syncHash.Window.Close()}
  378.     )
  379.     $syncHash.Window.Add_Closed({
  380.         Write-Verbose 'Halt runspace cleanup job processing'
  381.         $jobCleanup.Flag = $False
  382.  
  383.         #Stop all runspaces
  384.         $jobCleanup.PowerShell.Dispose()      
  385.     })
  386.     #endregion Window Close
  387.    
  388.  
  389.    
  390.  
  391.     #$syncHash.Window.Activate()
  392.     $syncHash.Window.ShowDialog() | Out-Null
  393.     $syncHash.Error = $Error
  394. })
  395. $psCmd.Runspace = $newRunspace
  396. $data = $psCmd.BeginInvoke()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement