Pages

Wednesday, 2 August 2017

PowerShell PowerShots-2.0

Here is a continued collection of PowerShell PowerShots. If you have any to contribute, contact me @TheTeeStar

As always feel free to play, alter and tinker with them!

# Run this first to define Computer variable
# If Computer variable is null, set it to localhost
   If (! $Computer) {$Computer= $env:COMPUTERNAME}

# Submitted by VRDSE via Reddit
# Demonstrate the power of the pipeline
   Get-Service -ComputerName $Computer | Where-Object -Property Status -EQ -Value Stopped | Start-Service -PassThru | Select-Object -Property MachineName,DisplayName,Status

  Get-Process | Where-Object -Property Company -EQ -Value 'Microsoft Corporation' | Sort-Object -Property WorkingSet64 -Descending | Select-Object ProcessName,@{Name='MemoryUsageMB';Expression={[math]::round($PSItem.WorkingSet64/1MB,0)}} | Select-Object -First 10 | ConvertTo-Csv | Out-File -FilePath $env:TEMP\TopProcesses.csv

# Get Serial Number Service Tag
   $Name=(Get-WmiObject  Win32_Bios).SerialNumber

# CPUName
   $CPUName=(Get-WmiObject  win32_Processor -ComputerName $Computer ).name

# Get-PysicalDrives
   ((Get-WmiObject -ComputerName $Computer -class Win32_LogicalDisk) | Where-Object {$_.DriveType -eq "3"})| Select-Object DeviceID,FreeSpace

# Get-NetworkDrives
   ((Get-WmiObject -ComputerName $Computer -class Win32_LogicalDisk) | Where-Object {$_.DriveType -eq "4"})| Select-Object DeviceID,FreeSpace

# Search Event Logs for logon failure 
  $Events=Get-WinEvent -FilterHashtable @{LogName='Security';ID=4625} -MaxEvents 500 -ComputerName $Computer

# Install IIS on client workstations
# Allow Http(s) rule
   New-NetFirewallRule -DisplayName "Allow HTTPS -Inbound" -Profile @('Domain','Private') -Direction Inbound -Action Allow -Protocol TCP -LocalPort @('80','443')
# Install IIS on client
   Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole

# Get RDP Port
   Function Get-RDPPort
     {
      $Port=Get-ItemProperty -Path Registry::"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" |Select-Object -ExpandProperty  PortNumber
        $MyObject= New-Object PSObject
        $MyObject | Add-Member NoteProperty Port    $Port
        Return $MyObject
     }

# Set RDP Port
  Function Set-RDPPort ($Port)
     {
           Try
              {
              Set-ItemProperty -Path Registry::"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name "PortNumber" -Value $Port      
              }
           Catch
              {
               Write-Output "Error setting port number $Port"
               Return $False
              }
     # Add firewall rule
        New-NetFirewallRule -DisplayName "Allow RDP-$Port" -Direction Inbound -Action Allow -EdgeTraversalPolicy Allow -Protocol TCP -LocalPort $Port -ErrorAction SilentlyContinue | Out-Null
           Try
              {
               Restart-Service -Name TermService  -Force
              }
          Catch
             {
              Write-Output "Error restarting services`n"
              Return $False
             }

           Write-Output "Successfully set port number to $Port, set new firewall rule and restarted Remote Desktop Services."
           Return $true
 }

# Enable-RDP
   Function Enable-RDP
         {
          Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0
          Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
          Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1
          Restart-Service -Name TermService  -Force
         }

# Get IPInfo from Active Directory computers
   $Computers=(Get-ADComputer -Filter *).DNSHostName
   $NetInfo  =Get-NetAdapter -Name * -CimSession $Computers -ErrorAction SilentlyContinue | Where-Object {$_.Status -match "Up"} |Select-Object ifindex,InterfaceAlias,MacAddress,PsComputerName | Sort-Object -Property PSComputerName



Wednesday, 26 July 2017

PowerShell PowerShots-1.0

Anyone who works in IT for any amount of time has used PowerShell. It provides an exceptional way of configuring workstations and servers through scripts and automation.
One of the great things about PowerShell is seemingly unlimited ability to create unique solutions, either through a few lines of code or creative functions.

Here is a collection of what I call PowerShell PowerShots, definitely a work in in progress.

Try them out, play with them for a

# Creates Windows input box 
   [Reflection.assembly]::loadwithpartialname("microsoft.visualbasic") | Out-Null
   [Microsoft.VisualBasic.interaction]::Msgbox("My Msg", "OkCancel,Critical", "My Title")

# Function Show-Msgbox 
# Returns user selected value from developer selected options
   Function Show-Msgbox ($Msg,$Button,$Icon,$Title)
{
          <#
          Button Values->OkOnly, OkCancel, AbortRetryIgnore, YesNoCancel, YesNo, RetryCancel
         Icon Values   ->Critical, Question, Exclamation, Information
#>
[reflection.assembly]::loadwithpartialname("microsoft.visualbasic") | Out-Null
$Result=[microsoft.visualbasic.interaction]::Msgbox($Msg, "$Button,$Icon", $Title)
     Return $Result
}

# Usage
   $MyResult=Show-Msgbox "My Msg" "OkCancel" "Critical" "My Title"

# If Computer variable is null, set it to localhost
   If (! $Computer) {$Computer= $env:COMPUTERNAME}

# Show-Ram in GB
   $TotalRam=(((Get-WmiObject -Class win32_physicalmemory -ComputerName $Computer | Measure-Object -Property capacity -Sum).Sum) / 1GB)

# Find DHCPServer 
  $DHCPServer=(Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DHCPEnabled -eq $true -and $_.DHCPServer -ne $null}).DHCPServer

# Get-DHCPLeases. Returns false on error
   Function Get-DHCPLeases ($Computer)
{
     Try
{
$DHCPScope=Get-DhcpServerv4Scope -ComputerName $Computer -ErrorAction Stop
$DHCPLeases=Get-DhcpServerv4Lease -ComputerName $Computer  -ScopeId ($DHCPScope.ScopeID.IPAddressToString) -ErrorAction Stop
}
Catch
{
         $DhcpLeases=$false
}
    Return $DhcpLeases
}
# Useage-Call Get-DHCP function and pass the Find DHCPServer
  Get-DHCPLeases ((Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DHCPEnabled -eq $true -and $_.DHCPServer -ne $null}).DHCPServer)