Mark Minasi's Tech Forum
Sign up Calendar Latest Topics
 
 
 


Reply
  Author   Comment  
jsclmedave

Administrator
Registered:
Posts: 488
Reply with quote  #1 

PowerShell script that our interns ( Greyson Paris ) is working on.

He has been working with PowerShell for about two months.  

He finished Don's "PowerShell In A Month Of Lunches" and he has taken off from there.

Greyson has opened an account here and will be able to answer any questions.


Open for suggestions...




## Idea, use this instead of the scriptblock in jobs. Just casually call reboot-etc. and have the parent function just handle the dataflow 

<#
.Synopsis
Restarts workstations running nimsoft "nimbus" service; updates sharepoint file.

.DESCRIPTION

.EXAMPLE
restart-nimworkstation -caCred example.xml -spcred otherExample.xml

.NOTES
Original Authors:

Mike F Robbins
Website: http://mikefrobbins.com
Twitter: @mikefrobbins
PowerShell Function to Create CimSessions to Remote Computers with Fallback to Dcom
http://mikefrobbins.com/2014/08/28/powershell-function-to-create-cimsessions-to-remote-computers-with-fallback-to-dcom/

Jeff Hicks
Website: http://jdhitsolutions.com/blog/
Twitter: @JeffHicks
PowerShell Problem Solver: Finding Installed Software Using CIM Cmdlets
https://www.petri.com/powershell-problem-solver-finding-installed-software-part-4

Richard Siddaway
Website: https://richardspowershellblog.wordpress.com/
Twitter: @RSiddaway
Registry Cmdlets: Working with the Registry
http://blogs.technet.com/b/heyscriptingguy/archive/2015/02/02/registry-cmdlets-manage-the-registry.aspx
Hey, Dude! Where Are My Methods?
http://blogs.technet.com/b/heyscriptingguy/archive/2013/09/20/hey-dude-where-are-my-methods.aspx

.LINK

#>


  [CmdletBinding()]
  [OutputType([int])]
  param (
    ## blocked out for testing purposes
        [Parameter(Mandatory = $true)]
        [String]
        $caXML,
        [Parameter(Mandatory = $true)]
        [String]
        $spXML
  )

  $date = Get-Date -Format MM-dd-yyyy
  $opt = New-CimSessionOption -protocol DCOM
    
  $spCreds = Import-Clixml $spXML
  $caCreds = Import-Clixml $caXML
    
  $spURI = 'https://BigDog.contact.Minasi.net/global/TS/CHS/GlobalPlatformServices/EnterpriseTools/Shared%20Documents/Public/Tools%20Engineering/CTO%20Dashboard/Logs/RestartRobotSummary.csv'
  $spLocalCopy = 'c:\temp\RRSummary.csv'
 
  ## get stuff from sharepoint
  Download-File -Path $spLocalCopy -URI $spURI -creds $spCreds

  $SummaryHash = Import-HashFromCSV -hashkey 'hostname' -path $spLocalCopy
  #$summaryHash | Add-Member -NotePropertyName $date
  ## run reboot-nimworkstation, capture problem servers ( will have to check later to test if $restartFaults is null )
  $Report = reboot-nimworkstation -InputHash $SummaryHash -Creds $caCreds 
  
  ## Report is an array; its indices 0,1,2 correspond to lists of servers that were [restarted successfully, failed to restart, could not be reached]
  foreach ($srv in $Report[0].values){
       $CS = New-CimSession -ComputerName $srv.target -SessionOption $opt -Credential $caCreds
       if( $null -eq $CS ){
          write-verbose "Failure to open CIM session : $hostname"
          $summaryHash[$srv.Hostname] | Add-Member -type NoteProperty -Name $date -Value '[ERROR] New-CimSession failure' -Force
          continue
       } 
       $myService = Get-CimInstance -CimSession $CS win32_service -filter "Name='NimbusWatcherService'" | Select-Object -Property Name, Status, State
              
        if( $myService.state -ne 'Running'){ 
            Write-Verbose "service isn't running, attempting service restart."
            Get-CimInstance -CimSession $CS win32_service -filter "Name='NimbusWatcherService'" | Invoke-CimMethod -Name StartService  
            
            Start-Sleep -Seconds 3            
            $myService = Get-CimInstance -CimSession $CS win32_service -filter "Name='NimbusWatcherService'" | Select-Object -Property Name, Status, State
        }
              
        $summaryHash[$srv.Hostname] | Add-Member -type NoteProperty -Name $date -Value $myService.State -force
        Remove-CimSession -CimSession $CS
  }
  foreach ($srv in $Report[1].values){
      
      $CS = New-CimSession -ComputerName $srv.target -SessionOption $opt -Credential $caCreds
      if( $null -eq $CS ){
        write-verbose "Failure to open CIM session : $hostname"
        $summaryHash[$srv.Hostname] | Add-Member -type NoteProperty -Name $date -Value '[ERROR] New-CimSession failure' -Force
        continue
      } 
      Get-CimInstance -CimSession $CS win32_service -filter "Name='NimbusWatcherService'" | Invoke-CimMethod -Name StopService 
      do{    
          $serviceOut = Get-CimInstance -CimSession $CS win32_service -filter "Name='NimbusWatcherService'" | Select-Object -Property State
            
          if( $serviceOut -eq $null ){ 
              write-verbose "Issue with stopping service for $hostname"
              Remove-CimSession -CimSession $CS
                  
              # Add to summary output
              $summaryHash[$srv.Hostname] | Add-Member -type NoteProperty -Name $date -Value '[ERROR] Failure restarting service' -SecondValue
                  
              break
          }
          Write-Verbose "waiting for service to stop : $hostname"
      } until ($serviceOut.State -eq 'Stopped') #ensure the service was actually stopped since it takes time.
              
      Write-Verbose "Attempting service Restart : $hostname"
      Get-CimInstance -CimSession $CS win32_service -filter "Name='NimbusWatcherService'" | Invoke-CimMethod -Name StartService 
      Start-Sleep -Seconds 3
      $myService = Get-CimInstance -CimSession $CS win32_service -filter "Name='NimbusWatcherService'" | Select-Object -Property Name, Status
     
      $summaryHash[$srv.Hostname] = $myService.State
      Remove-CimSession -CimSession $CS
  }
  foreach ($srv in $Report[2].values){
      $summaryHash[$srv.Hostname] | Add-Member -type NoteProperty -Name $date -Value '[ERROR] Unreachable' -force
  }
  $summaryHash.Values | Export-Csv $spLocalCopy -notypeinformation -Force 
  Upload-File -URI $spURI -Path $spLocalCopy -Creds $spCreds
function Download-File{
  Param(
    [Parameter(Mandatory = $true)]
    $Path,
    
    [Parameter(Mandatory = $true)]
    $URI,
    
    [Parameter(Mandatory = $true)]
    $Creds
  )
  ## Remove outdated server list
    if (Test-Path $Path){
       Remove-Item $Path
    }
    ## Download summary file from Sharepoint downloads new serverlist
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls
    $webclient = New-Object -TypeName System.Net.WebClient
    $webclient.Credentials = $Creds
    $webclient.DownloadFile($URI, $Path)
}
function Upload-File{
  Param(
      [Parameter(Mandatory = $true)]
      $Path,
    
      [Parameter(Mandatory = $true)]
      $URI,
    
      [Parameter(Mandatory = $true)]
      $Creds
    )
      [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls
      $webclient = New-Object -TypeName System.Net.WebClient
      $webclient.Credentials = $Creds
      $webclient.UploadFile($URI, 'PUT', $Path)
}
function Import-HashFromCSV {
  Param(
     [Parameter(Mandatory = $true)]
     $HashKey,
     
     [Parameter(Mandatory = $true)]
     $Path
  )
    ## Push summary contents into hash table -
    $ImportArr = Import-Csv $Path
    $OutHash = @{}
    foreach( $row in $ImportArr ) 
    {
        $OutHash[$row.$HashKey] = $row
    }
    Write-Output $OutHash
}
workflow Reboot-NimWorkstation {
  param (
    [parameter(Mandatory = $true)]
    $InputHash,
    
    [parameter(Mandatory = $true)]
    $Creds
  )
  $Passhash = @{}
  $FailHash = @{}
  $UnreachableHash = @{}
  $Credential = $creds
  
  foreach -parallel ( $srv in $inputHash.Values ){
    
    if     ($null -eq $srv.ipv4){$target = $srv.Hostname}
    elseif ($srv.ipv4 -ne 'n/a'){$target = $srv.ipv4}
    else                        {$target = $srv.hostname}
    
    
    
    if (Test-Connection -ComputerName $Target -count 1 -quiet){
    
      $hashObj = New-Object -type PSObject -Property  @{ 
          Hostname = $srv.Hostname
          IPv4     = $srv.IPv4
          Target   = $target
         }
   
      Try { 
      
        inlinescript 
          { ## might not have to "-wait -for" considering we're running TONS of servers. might make it run even faster, clear up threads etc. 
            restart-computer -computername $Using:target -Credential $Using:Credential -wait -for Wmi -Protocol dcom -ErrorAction stop
          }
          
        Write-Verbose "$target restart passed"
       $Workflow:passHash = $Workflow:PassHash + @{ $srv.hostname = $hashObj }
      }
    
      catch{
        Write-Verbose "$target restart failed"
        $Workflow:failHash = $Workflow:failHash + @{ $srv.hostname = $hashObj }
      
      }
    }
    else{
      Write-Verbose "$target is unreachable"
       $Workflow:UnreachableHash = $Workflow:UnreachableHash + @{ $srv.hostname = $hashObj }
    }
            
  }## End Foreach -para
  $ReportArr = $Passhash, $FailHash, $UnreachableHash
  Write-Output $ReportArr
}


__________________
Tim Bolton @jsclmedave
Email: [string](0..20|%{[char][int](32+('527377347976847978324785847679797514357977').substring(($_*2),2))}) -replace ' '  

New to the forum? Please Read this
0
Tefferon

Still Checking the Forum Out
Registered:
Posts: 2
Reply with quote  #2 
Thanks for the introduction Tim!

As he said, I'm new to PowerShell and I'm learning more every day. This past week I've been exploring workflows, and the weeks before that I was heavy into CIM/WMI and registry manipulation. I'm always open for critiques and best practice tips. Nice to meet you all!

__________________
Greyson
0
Infradeploy

Avatar / Picture

Senior Member
Registered:
Posts: 171
Reply with quote  #3 
Welcome to the forum sir.
__________________
Have SpaceSuit, Will Travel

0
Previous Topic | Next Topic
Print
Reply

Quick Navigation:

Easily create a Forum Website with Website Toolbox.