Wednesday, October 30, 2013

Find amount of time since Windows started

Whether you need to find out the time since a computer was turned on for ticketing purposes, just out of curiosity or to show off how long your server has been online to a friend, you have come to the right place. Here is a PowerShell function to find out how many Days, Hours, and Minutes since the machine was started.

Copy the below code into a PowerShell window.
<#
.CREATED BY:
    Chris Davis
.MODIFIED BY:
    Matthew A. Kerfoot
.MODIFIED ON:
    10\30\2013
.Synopsis
   Outputs how long since the last reboot
.DESCRIPTION
    This function gathers information regarding when $ComputeName was last rebooted. `
.EXAMPLE
   Get-Uptime localhost | ConvertTo-Html | Out-File C:\
   Referance - http://pc-addicts.com/my-powershell-scripts/
#>

function Get-Uptime { [CmdletBinding()]

param ( [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
           [string]$ComputerName = "$env:COMPUTERNAME" )

Begin { $OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computername
        $diff = $OS.ConvertToDateTime($OS.LocalDateTime) - $OS.ConvertToDateTime($OS.LastBootUpTime) }

Process { foreach ( $_ in $ComputerName ){ 
                   @{ "ComputerName" = $Computername
                      "Days" = $diff.Days
                      "Hours" = $diff.Hours
                      "Minutes" = $diff.Minutes } } }

End { New-Object -TypeName PSObject -Property $properties | Format-Table -AutoSize }}

Once the above code is pasted into a PowerShell prompt hit enter a couple times and type, 'Get-Uptime'.
[www.matthewkerfoot.com]> Get-Uptime
Name                           Value
----                           -----
Hours                          5
Days                           0
ComputerName                   VT-MKERFOOT-W8
Minutes                        52

PS [www.matthewkerfoot.com]>

Tuesday, October 29, 2013

Get all stopped services that are set to autostart

Have you ever wanted to check which services were set to run automatically at boot up but are currently stopped?

      

I find myself wanting to know this all to often, this is one of the first things I check when there is an issue with a service that a server is hosting. The below function will help you find out any and all services that have been configured to start automatically but are currently stopped or not running.





Copy\Paste the below code into a PowerShell window.
<#
.CREATED BY:
    Matthew A. Kerfoot
.CREATED ON:
    10\29\2013
.Synopsis
   Finds Services set to start automatically but are stopped
.DESCRIPTION
   This function will find all services that are set to start automatically at startup but are not currently running.
.EXAMPLE
   Get-Stopped -ComputerName localhost | Out-file "$env:USERPROFILE\Desktop\StoppedServices.txt"
#>

function Get-Stopped {

                      [CmdletBinding()]
              Param ( [Parameter(Mandatory=$false,
                      ValueFromPipelineByPropertyName=$true,
                      Position=0)]
                      $Computername )

         Begin { $Obj = Get-WmiObject -Class Win32_Service }

     Process { $Stopped = $Obj | Where-Object { ($_.StartMode -eq "Auto") -and ($_.State -eq "Stopped") } | 
              Select-Object Name, DisplayName, StartMode, State, Description }

 End { $Stopped | Format-Table -AutoSize }

}
Hit Enter a couple times and then type 'Get-Stopped' to get a table of all service that are set to start when windows boots yet are not running.
PS [www.matthewkerfoot.com]> Get-Stopped

Name           DisplayName                     StartMode State   Description
----           -----------                     --------- -----   -----------
gupdate        Google Update Service (gupdate) Auto      Stopped Keeps your Google software up to d
RemoteRegistry Remote Registry                 Auto      Stopped Enables remote users to modify reg
SCardSvr       Smart Card                      Auto      Stopped Manages access to smart cards read
sppsvc         Software Protection             Auto      Stopped Enables the download, installation
wuauserv       Windows Update                  Auto      Stopped Enables the detection, download, a

PS [www.matthewkerfoot.com]>
Now you can restart any service you feel should be running for example to start the Windows Update service just type, 'Get-Service -Name wuauserv | Start-Service -Verbose'.

Saturday, October 26, 2013

Get 10 CPU consuming processes

Here's a little function that finds the top 10 CPU consuming processes with a nice colorful output. Paste the below code into PowerShell.
<#
.CREATED BY:
    Matthew A. Kerfoot
.CREATED ON:
    10\25\2013
.Synopsis
   Gathers Top 10 CPU consuming processes.
.DESCRIPTION
    This function gathers all processes list them by highest CPU consumption and `
    then displays a nice colorfull display of the top 10 processes listed decending.
.EXAMPLE
   Get-TopCpu -computername localhost -color yellow
#>
Function Get-TopCpu {

            [CmdletBinding()]
    param ( [Parameter(ValueFromPipelineByPropertyName=$true,
            Position=0)]
            [string[]]$computername = $env:COMPUTERNAME,
            [string]$color = "Green"
          )

$num = 1
$Total = 10
$Cpu = Get-Process | Sort-Object CPU -Descending 
Hostname
 foreach ($_ in $Cpu) {
      If ($num -gt $Total) { break }
            write-host "$num) " -NoNewline
            write-host $_.Description  -foregroundcolor "$color" -NoNewline
            write-host " - CPU:"$_.CPU
            $num += 1 }

 Get-WmiObject win32_processor | select LoadPercentage  | fl
}
Get-TopCpu

Hit Enter a couple times and then type 'Get-TopCpu'.

Thursday, October 24, 2013

Server Core to full Windows Server

     Have you ever logged onto a server that has Server Core installed? Did you know how to make the changes you logged on the server to make? Well if not here is a simple step-by-step guide on converting a Windows Server Core installation to the full Windows Server with a GUI.

So we begin with just a command prompt...


c:\Users\Administrator>
Then lets open up PowerShell by Typing 'powershell.exe' or just 'powershell' for short.
c:\Users\Administrator>powershell
TIP : 'powershell.exe -RunAs' opens an elavated PowerShell prompt.
c:\Users\Administrator>powershell
Windows PowerShell
Copyright (C) 2012 Microsoft Corporation. All rights reserved.
PS C:\Users\Administrator>
It's time to install "The Shell" first things first, lets find out which features are needed. To do this I usually utilize the 'Get-WindowsFeature' cmdlet with the '-Name' parameter to search the Windows Feature I'm looking for like this 'Get-WindowsFeature -Name *Server-GUI*'.
PS C:\users\Administrator> Install-WindowsFeature Server-Gui-Shell,Server-Gui-Mgmt-Infra -restart
Break time: Go get a coffee this will take a couple minutes to install and then restart.
Welcome to Windows Server full GUI!

Tuesday, October 22, 2013

PowerShell Error Handling

whoops
In this Video I will show you how to change the color of the error font.

Kaseya Alert – Pages/Sec

Have you ever received an alert from Kaseya? If you answered yes, you’ve came to the right place, I too have seen what feels like thousands of tickets like the one pictured below.

Image
Luckily for us With PowerShell we can easily reverse engineer a ticket like above. Notice the ‘Log Object Name’ which in this case is ‘Pages/Sec’ with refers to memory consumption. From what I’ve noticed Kaseya monitors the specific performance counters which we can also monitor with PowerShell.
While logged onto the effected server run the following cmdlet in an Elevated PowerShell window.

(Get-Counter -ListSet Memory).Paths

PS C:\> (Get-Counter -ListSet Memory).paths
\Memory\Page Faults/sec
\Memory\Available Bytes
\Memory\Committed Bytes
\Memory\Commit Limit
\Memory\Write Copies/sec
\Memory\Transition Faults/sec
\Memory\Cache Faults/sec
\Memory\Demand Zero Faults/sec
\Memory\Pages/sec
\Memory\Pages Input/sec
\Memory\Page Reads/sec
\Memory\Pages Output/sec
\Memory\Pool Paged Bytes
\Memory\Pool Nonpaged Bytes
\Memory\Page Writes/sec
\Memory\Pool Paged Allocs
\Memory\Pool Nonpaged Allocs
\Memory\Free System Page Table Entries
\Memory\Cache Bytes
\Memory\Cache Bytes Peak
\Memory\Pool Paged Resident Bytes
\Memory\System Code Total Bytes
\Memory\System Code Resident Bytes
\Memory\System Driver Total Bytes
\Memory\System Driver Resident Bytes
\Memory\System Cache Resident Bytes
\Memory\% Committed Bytes In Use
\Memory\Available KBytes
\Memory\Available MBytes
\Memory\Transition Pages RePurposed/sec
\Memory\Free & Zero Page List Bytes
\Memory\Modified Page List Bytes
\Memory\Standby Cache Reserve Bytes
\Memory\Standby Cache Normal Priority Bytes
\Memory\Standby Cache Core Bytes
\Memory\Long-Term Average Standby Cache Lifetime (s)
PS C:\>

Notice \Memory\Pages/Sec
now run the below cmdlet to output the current \Memory\Pages/Sec.
Get-Counter \Memory\Pages/Sec
PS C:\> Get-Counter \Memory\Pages/sec

Timestamp                 CounterSamples
---------                 --------------
10/24/2013 1:40:02        \\vt-mkerfoot-w8\memory\pages/sec :
MATTHEW                   0

PS C:\>
I like to gather a little more information typically…

Hostname ; Get-Counter -Counter \Memory\Pages/sec -SampleInterval 1 -MaxSamples 3

PS C:\> hostname ; Get-Counter -Counter "\Memory\Pages/sec" -SampleInterval 1 -MaxSamples 3
VT-MKERFOOT-W8

Timestamp                 CounterSamples
---------                 --------------
10/24/2013 2:08:04        \\vt-mkerfoot-w8\memory\pages/sec :
MATTHEW                   1749.75083141259

10/24/2013 2:08:05        \\vt-mkerfoot-w8\memory\pages/sec :
MATTHEW                   1421.4409519757

10/24/2013 2:08:06        \\vt-mkerfoot-w8\memory\pages/sec :
MATTHEW                   4602.18149317241

PS C:\>

Find available disk space PERCENTAGE with PowerShell

       As an overnight admin I find myself constantly cleaning up full disk drives. Here's a little function I wrote to help myself and hopefully you speed up the process of finding out what percentage of disk space is free. I would recommend adding to your $PROFILE as I use this every night at work.
  
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
<#
.CREATED BY:
    Matthew A. Kerfoot
.CREATED ON:
    10\21\2013
.Synopsis
   Gathers Disk Drive Available FreeSpace Percentage
.DESCRIPTION
    This function gathers information about HDDs and then reformats the output `
    to an easy to read output with the available FreeSpace percentage.
.EXAMPLE
   Get-FreeSpace localhost | ConvertTo-Html | Out-File C:\
#>

function Get-FreeSpace {
                        [CmdletBinding()]
                 Param ([Parameter(Mandatory=$false,
                        ValueFromPipelineByPropertyName=$true,
                        Position=0)]
                        $Computername )

        Begin { $Begin = Get-WmiObject Win32_LogicalDisk }
                        

    Process { $Process = $Begin | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName, 
            @{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } },
            @{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f( $_.Size / 1gb)}},
            @{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) } },
            @{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Size ) } } }
                    
End { $Process | Format-Table -AutoSize }
}

Get-FreeSpace
 

Now to explain what exactly is happening in the above function:

 The above code allows us to only have to type “Get-FreeSpace” to get an output of the local machines available free space. The next important thing to point out is the Begin, Process and End Blocks which should be used just like you would think, put everything needed for the script(ex..Parameters,Variables). Next is the Process block, this is where you should be running a majority of the code especially with a lengthier script and finally the End block which I tend to use to clean everything up, maybe email it and add the final formatting adjustments.

This code will gather all information related to “Win32_LogicalDisk” and place it into "$Begin"
Begin { $Begin = Get-WmiObject Win32_LogicalDisk }

This code takes the $Begin variable and and pipes it into Where-Object { $_.DriveType -eq "3" }which will gather all information related to “Win32_LogicalDisk” and sort\filter everything gathered and only keep anything with a “drivetype” of 3 which means its a HDD and not a DVD drive or Flash drive for example.
Process { $Process = $Begin | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName, 

The below code looks a little frightening to a PowerShell newcomer however after just a little playing around with PS you will find expressions to be one of the more enjoyable tasks as an IT admin. I think the easiest way to understand expressions is to see one used in real life, let me show you.
Process { $Process = $Begin | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName, 
            @{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } },
            @{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f( $_.Size / 1gb)}},
            @{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) } },
            @{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Size ) } } }
Take a look at the expressions above and then the output in the below image...specifically follow Drive, Size, FreeSpace, and PercentFree, these are all case sensitive sensitive as in however you type it in the "@{ Name = "Drive"" area.
PS C:\Users\mkerfoot> Get-FreeSpace

SystemName     Drive Size (GB) FreeSpace (GB) PercentFree
----------     ----- --------- -------------- -----------
VT-MKERFOOT-W8 C:    223.2     37.5           16.8 %     

PS C:\Users\mkerfoot> 
Then I ended it off with some nice formatting for a presentable output.
End { $Process | Format-Table -AutoSize }
}
Example run
PS C:\Users\mkerfoot\Desktop\powershell\Functions> Get-FreeSpace

SystemName     Drive Size (GB) FreeSpace (GB) PercentFree
----------     ----- --------- -------------- -----------
VT-MKERFOOT-W8 C:    223.2     37.5           16.8 %