Thursday, April 26, 2012

Scripting Games 2012 Advanced Event 10

Advanced Event 10 :

<#
.DESCRIPTION
    This script creates csv log file for Processor counter set every 2 seconds (10 snapshots).
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/13/the-2012-scripting-games-advanced-event-10-create-a-csv-log-file.aspx
#>
param (
[string[]]$Computers=$env:computername
)
foreach ($computer in $computers)
{
    $filepath = $env:userprofile + "\Documents\" + $Computer + "_processorCounters.csv"
        Get-Counter -ListSet processor -ComputerName $Computer |
        Get-Counter -ComputerName $Computer -SampleInterval 2 -MaxSamples 10 |
        Export-Counter -path $filepath -FileFormat CSV -Force
}

Scripting Games 2012 Advanced Event 9

Advanced Event 9 :


<#
.DESCRIPTION
    This script perform inventory and export data to xml.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/12/the-2012-scripting-games-advanced-event-9-perform-an-inventory.aspx
#>

function Create-XML
{
Param ([Parameter(Mandatory=$true,
   ValueFromPipeline=$true)]$object)

@"
<ComputerInfo>
"@
    foreach ($p in $object |Get-Member -type *Property )
    {
        $Name  = $p.Name
        $Value = $Object.$Name   
@"
`t<$Name>$Value</$Name>`n
"@
     }
@"
</ComputerInfo>
"@
}

function HumanReadSize
{
    Param ([long]$Size)
if ($Size -ge 1Gb )
{
return ("{0:N2}" -f ($Size / 1Gb) + " GigaBytes")
}
elseif ($Size -ge 1Mb )
{
return ("{0:N2}" -f ($Size / 1Mb ) + " MegaBytes")
}
elseif ($Size -ge 1Kb )
{
return ("{0:N2}" -f ($Size / 1Kb ) + " KiloBytes")
}
elseif (($Size -ge 0 ) -and ($Size -lt 1Kb))
{
return ("{0:N0}" -f ($Size) + " Bytes")
}
}

$sum=0
$os= Get-WmiObject Win32_OperatingSystem
$comp = Get-WmiObject win32_ComputerSystem
$procs = Get-WmiObject win32_Processor
$nets = Get-WmiObject  win32_networkadapter -Filter "netenabled = true"
Get-WmiObject win32_physicalmemory | where {( $_.typedetail -ne 4096 )} | foreach {$sum += $_.capacity }

    $output = New-Object PSObject
    $output | Add-Member noteproperty ComputerName ($comp.Name)
    $output | Add-Member noteproperty DomainName ($comp.Domain)
    $output | Add-Member noteproperty Manufacturer ($comp.Manufacturer)
    $output | Add-Member noteproperty ComputerModel ($comp.Model)
    $output | Add-Member noteproperty NumberofProcessors ($comp.NumberOfProcessors)
    $output | Add-Member noteproperty Numberofcores ($comp.NumberOfLogicalProcessors)
$i=1
foreach ($proc in $procs)
{
   
    $output | Add-Member noteproperty "Speedofprocessors$i"  ($proc.MaxClockSpeed)
    $output | Add-Member noteproperty "ProcessorID$i" ($proc.ProcessorID)
    $i +=1   
}
$b=1
foreach ($net in $nets)
{
    $output | Add-Member noteproperty "MACAddress$b" ($net.MACAddress)
    $b += 1
}

    $output | Add-Member noteproperty Version ($os.Version)
    $output | Add-Member noteproperty Memory (HumanReadSize $sum)

$filepath = $env:userprofile + "\Documents\" + ($comp.Name) + "." + ($comp.Domain) + "." + (Get-date).tostring("yyyyMMdd") + ".xml"
$output | create-xml | Out-file $filepath

Scripting Games 2012 Advanced Event 8

Advanced Event 8 :

<#
.DESCRIPTION
    This script can enable and (or) disable wireless or ethernet adapter to prevent bridging on laptop computers.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/11/the-2012-scripting-games-advanced-event-8-enable-network-adapters.aspx
#>

function get-netadapter
{
  param ([string]$nettype= "%", $isEnabled=$null)
    if ($isenabled -eq $null)
    {
      $filter ="name like '$nettype'"
    }
    else
    {
      $filter ="name like '$nettype' and netenabled=$isenabled"
    }   
   return Get-WmiObject win32_networkadapter -Filter $filter
}

function enableadapter
{
  param ($enable=$true, $neta, $prev=$false)
    #enable adapters
    if ($enable)
    {
      if ($neta.count -gt 1)
      {
     
         foreach ($adapter in $neta)
         {
            do
            {
                $choice = Read-Host $adapter.description  " Enable Yes/No ?"
            }
            until ($choice -eq "yes" -or $choice -eq "no")
           
             If ($Choice -eq "yes")
             {
                if (!($prev))
                {
                    $adapter.enable()
                }
                else
                {
                    # for pre-vista os, even though netsh is working on post vista oss,
                    #it is fun using new method for these oss .enable() or .disable()
                    netsh interface set interface "$($adapter.netconnectionID)" ENABLED
                }
               
                return
             }   
          }
       }
       else
       {
          if (!($prev))
          {
             $neta.enable()
          }
          else
          {
                   
              netsh interface set interface "$($neta.netconnectionID)" ENABLED
           }
       }
   
    }
    #disable adpaters
    else
    {
      foreach ($adapter in $neta)
      {
     
                if (!($prev))
                {
                    $adapter.disable()
                }
                else
                {
                    netsh interface set interface "$($adapter.netconnectionID)" DISABLED
                }
      }
     }
}

    $identity  = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object System.Security.Principal.WindowsPrincipal( $identity )
   
        if (!($principal.IsInRole( [System.Security.Principal.WindowsBuiltInRole]::Administrator )))
        {
            write-host "Warning: You're not running this script using elevated shell. You will not be able to run this script without administrative permission."
            exit
   
        }
       
   $os = Get-WmiObject Win32_OperatingSystem
    if ($os.version -match "5.")
    {
        $prevista=$true
    }
    else
    {
        $prevista=$false
    }
   
    $comp = Get-WmiObject win32_ComputerSystem
    #It is a laptop   
     if ($comp.PCSystemType -eq 2)
     {
         #check for enabled wireless and ethernet adapters
         $wless=@()
         $wless = @(get-netadapter "%wireless%" $true)
         $ether=@()
         $ether = @(get-netadapter "%ethernet%" $True)
            #wireless adapters not enabled and ethernet adpaters enabled
            if ($wless.Count -eq 0 -and $ether.Count -gt 0)
            { 
                #disable ethernet adapters
                enableadapter $false $ether $prevista
                #enable wireless adapter
                enableadapter $True (get-netadapter "%wireless%" $false) $prevista
   
            }
            #wireless adapter(s) enabled and ethernet adpaters disabled
            elseif ($wless.Count -gt 0 -and $ether.Count -eq 0)
            {
               #disable wireless adapters
                enableadapter $false $wless $prevista
                #enable ethernet adapter
                enableadapter $True (get-netadapter "%ethernet%" $false) $prevista
            }
            # no ethernet or wireless enabled
            elseif ($wless.Count -eq 0 -and $ether.Count -eq 0)
            {
                do
                {
                    $choice = Read-Host "Ethernet and Wireless adapters are disabled.Enable Wireless adapter Yes/No ?"
                }
                until ($choice -eq "yes" -or $choice -eq "no")
           
                If  ($choice -eq "yes")
                {
                    Write-Host "Enabling wireless adapters ..."
                    enableadapter $True (get-netadapter "%wireless%" $false) $prevista
                }
                else
                {
                    Write-Host "Enabling ethernet adapters ..."
                    enableadapter $True (get-netadapter "%ethernet%" $false) $prevista
                }
      
            }
            # ethernet and wireless enabled
            elseif ($wless.Count -gt 0 -and $ether.Count -gt 0)
            {
                do
                {
                    $choice = Read-Host "Ethernet and Wireless adapters are enabled.Disable Wireless adapter Yes/No ?"
                }
                until ($choice -eq "yes" -or $choice -eq "no")
           
                If  ($choice -eq "yes")
                {
                    Write-Host "Disabling wireless adapters ..."
                    enableadapter $false (get-netadapter "%wireless%" $true) $prevista
                }
                else
                {
                    Write-Host "Disabling ethernet adapters ..."
                    enableadapter $false (get-netadapter "%ethernet%" $true) $prevista
                }
      
            }
        }
        else
        {
            Write-Host "This script is only for laptops !"
        }

Scripting Games 2012 Advanced Event 7

Advanced Event 7 :

<#
.DESCRIPTION
    This script reports latest events from all event logs.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/10/the-2012-scripting-games-advanced-event-7-search-windows-logs.aspx
#>
$obj=@()
Get-WinEvent -ea silentlycontinue -ListLog * -Force | where { $_.isEnabled -eq $true } `
         | foreach {
                        if (!(($_.logtype -eq "analytical") -or ($_.logtype -eq "debug")))
                        {
                          
                            $obj += (Get-WinEvent -ea silentlycontinue -LogName $_.logname -MaxEvents 1 `
                                                     | Select-Object TimeCreated,Logname,ID,Message)  
                           
                        }
                        else
                        {
                            $debevents=@()
                            $debevents = (Get-WinEvent -ea silentlycontinue -LogName $_.logname -Force -Oldest `
                                                    | Select-Object TimeCreated,Logname,ID,Message )
                            $obj += $debevents[-1]
                        }
                  
                   }
         
Write-Output $obj | Sort-Object timecreated -Descending | Fl *
               

Scripting Games 2012 Advanced Event 6

Advanced Event 6 :

<#
.DESCRIPTION
    This script reports information about multiple servers uptime.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/09/2012-scripting-games-advanced-event-6-compute-uptime-for-multiple-servers.aspx
.PARAMETER Computers
    Name of the remote computer, if omitted localhost will be used.
.EXAMPLE
    event6.ps1
    To collect information about error events from local computer, run the script without parameters.
.EXAMPLE
    event6.ps1 "computer1","computer2"
    To collect information about error events on remote computers.
#>

param (
[string[]]$Computers=$env:computername
)
[datetime]$Reptime=(Get-Date -UFormat %D).tostring() + " 08:00:00"
Foreach ($server in $computers)
{
    $os= Get-WmiObject -ea silentlycontinue Win32_OperatingSystem -ComputerName $server
    #check if $os is not null
    if (!($os -eq $null))
    {
       $reboot =$os.ConvertToDateTime($os.LastBootUpTime)
       
        $obj  = New-Object -TypeName PSObject
            if ( $Reptime -ge $reboot )
            {
                $dif = $reptime.Subtract($reboot)
                $obj | Add-Member NoteProperty Computername $server
                $obj | Add-Member NoteProperty Days $dif.days
                $obj | Add-Member NoteProperty Hours $dif.hours
                $obj | Add-Member NoteProperty Minutes $dif.minutes
                $obj | Add-Member NoteProperty Seconds $dif.seconds
                $obj | Add-Member NoteProperty Date $reboot.ToShortDateString()
       
            }
            else
            {
                $obj | Add-Member NoteProperty Computername $server
                $obj | Add-Member NoteProperty Days 0
                $obj | Add-Member NoteProperty Hours 0
                $obj | Add-Member NoteProperty Minutes 0
                $obj | Add-Member NoteProperty Seconds 0
                $obj | Add-Member NoteProperty Date $null
            }

            $filepath = $env:userprofile + "\Documents\" + $Reptime.ToString("yyyyMMdd") + "_Uptime.csv"
                If (Test-Path($filepath))
                {
                    $obj |ConvertTo-Csv -OutVariable OutData -NoTypeInformation
                    $OutData[1..($OutData.count - 1)]  | ForEach-Object {Add-Content -Value $_ -Path $filepath}
                }
                else
                {
                    $obj | Export-Csv -NoTypeInformation -Path $filepath
                }
     }  
}

Scripting Games 2012 Advanced Event 5

Advanced Event 5:

<#
.DESCRIPTION
    This script reports information about error events on local and remote computers.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/06/2012-scripting-games-advanced-event-5-list-errors.aspx
.PARAMETER Computers
    Name of the remote computer, if omitted localhost will be used.
.EXAMPLE
    event5.ps1
    To collect information about error events from local computer, run the script without parameters.
.EXAMPLE
    event5.ps1 "computer1","computer2"
    To collect information about error events on remote computers.
#>
param (
[string[]]$Computers=$env:computername
)
   
    $identity  = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object System.Security.Principal.WindowsPrincipal( $identity )
if (!($principal.IsInRole( [System.Security.Principal.WindowsBuiltInRole]::Administrator )))
{
    write-host "Warning: You're not running this script using elevated shell. You will not be able to access event logs that require Administrator permission."
}
Foreach ($server in $computers)
{
    Write-Host ""
    Get-WinEvent -listlog * -ea SilentlyContinue -ComputerName $server| Where-Object { $_.IsClassicLog -eq $true } | foreach {   
           
            write-host ($server + "  " + $_.logname) -BackgroundColor darkGray
           
            Get-WinEvent -ea silentlycontinue -ComputerName $Server -FilterHashtable @{logname = $_.logname ; level=2 } | `
                                              Group-Object Providername -NoElement | `
                                              Sort-Object Count -descending
    }
   
}

Scripting Games 2012 Advanced Event 4

Advanced Event 4:


function HumanReadSize
{
    Param ([long]$Size)
if ($Size -ge 1Gb )
{
return ("{0:N2}" -f ($Size / 1Gb) + " GigaBytes")
}
elseif ($Size -ge 1Mb )
{
return ("{0:N2}" -f ($Size / 1Mb ) + " MegaBytes")
}
elseif ($Size -ge 1Kb )
{
return ("{0:N2}" -f ($Size / 1Kb ) + " KiloBytes")
}
elseif (($Size -ge 0 ) -and ($Size -lt 1Kb))
{
return ("{0:N0}" -f ($Size) + " Bytes")
}
}

function Get-FolderSize {
<#
.SYNOPSIS
    This script reports information about folder space.
.DESCRIPTION
    This script reports information about folder space.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/05/the-2012-scripting-games-advanced-event-4-determine-folder-space.aspx 
.PARAMETER Path
    Path of the root folder.
.EXAMPLE
    "c:\windows"| get-foldersize 
.EXAMPLE
    get-foldersize "c:\windows" | Sort-Object Folder
#>

[CmdletBinding()]
param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][string]$path)

BEGIN {}

PROCESS {
if (!(test-path $path))
{
Write-Output "Folder does not exist"
return
}
$f=@()
    #Calculating the root folder size
     $rootItems = (Get-ChildItem $path -recurse -Force | Measure-Object -property length -sum)
     $sumroot = HumanReadSize $rootItems.sum
    
        $obj  = New-Object -TypeName PSObject
        $obj | Add-Member -MemberType NoteProperty -Name Folder -Value $path
        $obj | Add-Member -MemberType NoteProperty -Name "Size of Folder" -value $sumroot
        $f +=$obj
    #Calculating the root subfolders size
$colItems = (Get-ChildItem $path -recurse | Where-Object {$_.PSIsContainer -eq $True} )
foreach ($i in $colItems)
    {
        $subFolItems = (Get-ChildItem $i.FullName -recurse -Force | Measure-Object -property length -sum)
        $sumsubfol = HumanReadSize $subFolItems.sum
     
        $obj  = New-Object -TypeName PSObject
        $obj | Add-Member -MemberType NoteProperty -Name Folder -Value $i.FullName
        $obj | Add-Member -MemberType NoteProperty -Name "Size of Folder" -value $sumsubfol
        $f +=$obj
    }
   
           Write-Output $f
}
END {}
}

Scripting Games 2012 Advanced Event 3

Advanced Event 3:

<#
.DESCRIPTION
    This script create log information that updates information about OS,User ...
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/04/2012-scripting-games-advanced-event-3-create-a-log-that-updates.aspx  
#>
$os= Get-WmiObject Win32_OperatingSystem
$comp = Get-WmiObject win32_ComputerSystem
$net = Get-WmiObject Win32_NetworkLoginProfile | sort -descending LastLogon | select * -first 1
$prn = Get-WmiObject win32_printer -Filter "Default=True"
$mappeddrives=Get-WmiObject win32_logicaldisk -filter "DriveType=4" | `
              Select-Object @{Name="Drive Letter";Expression={$_.DeviceID}}, `
                            @{Name="Resource Path";Expression= {$_.ProviderName}}
$output = New-Object PSObject
$output | Add-Member noteproperty LastReboot ($os.ConvertToDateTime($os.LastBootUpTime))
$output | Add-Member noteproperty ComputerName (($comp.DNSHostname) + "." + ($comp.Domain))
$output | Add-Member noteproperty Username ($comp.Username)
$output | Add-Member noteproperty OperatingSystemVersion ($os.Version)
$output | Add-Member noteproperty CurrentLog ($os.ConvertToDateTime($net.LastLogon))
$output | Add-Member noteproperty OperatingSystemServicePack ([string]($os.ServicePackMajorVersion) + "." + `
                                                              [string]($os.ServicePackMinorVersion))
$output | Add-Member noteproperty DefaultPrinter ($prn.Name)
$output | Add-Member noteproperty Drive $mappeddrives
$output | Add-Member noteproperty TypeofBoot ($comp.bootupstate)

$output| Out-File -append ($os.Systemdrive + "\logonlog\logonstatus.txt")

Scripting Games 2012 Advanced Event 2

Advanced Event 2:

<#
.DESCRIPTION
    This script reports information about remote and local services.
.LINK
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/03/2012-scripting-games-advanced-event-2-find-information-about-remote-and-local-services.aspx 
.PARAMETER Computername
    Name of the remote computer, if omitted localhost will be used.
.PARAMETER User
    User account in form of "domain\user" with administrative permissions.
.EXAMPLE
    event2.ps1
    To collect information about local services from local computer, run the script without parameters.
.EXAMPLE
    event2.ps1 computer1 domain1\administrator
    To collect information about services running on remote computer, run the script with remote comuter name ex.Computer1 and username with administrative credential
#>
##
# Start of Script
##
param (
[string]$Computername=$env:computername,
[string]$User
)
try
{
    If (($Computername -match $env:computername) -or ($Computername -match "localhost"))
{
        Get-WmiObject -ErrorAction Stop win32_service -ComputerName $Computername | Select-Object __Server,name,Startmode,State,Startname | Export-Csv myservicestatus.csv -NoTypeInformation
}
    else
{
       
        Get-WmiObject -ErrorAction Stop win32_service -ComputerName $Computername -Credential $user | Select-Object __Server,name,Startmode,State,Startname | Export-Csv myservicestatus.csv -NoTypeInformation
}
}
catch [Exception]
{
  if ($Error[0].Exception.Message -match "Access denied.")
    {
        Write-host "Current windows credential do not allow for access to WMI on $computername. Please run with administrative credentials." 
 
    }
}

Scripting Games 2012 Advanced Event 1

Scripting Games 2012 are almost over, only waiting for judges to grade submitted scripts. I'll publish all of mine scripts for advanced events. Here is my script for advanced event 1:

http://blogs.technet.com/b/heyscriptingguy/archive/2012/04/02/the-2012-scripting-games-advanced-event-1-review-a-coworker-s-script.aspx

for ($i = 1 ; $i -le 10 ; $i++)

{
start-sleep 1
$notepad = Get-Process notepad -erroraction silentlycontinue
$notepad
}

Tuesday, April 10, 2012

The processing of Group Policy failed. Event ID 1096

In my case there was a machine with bad sectors on hard disk and group policy settings were failing to apply. In System Event Log there was error event id 1096 :

The processing of Group Policy failed. Windows could not apply the registry-based policy settings for the Group Policy object LocalGPO. Group Policy settings will not be resolved until this event is resolved. View the event details for more information on the file name and path that caused the failure.
After imaging the hard disk with new one (bad sector free), group policy settings were still failing to apply. Since this machine had bad sectors, there was a problem with local policy file. So, after renaming registry.pol into registry.bak from c:\Windows\System32\GroupPolicy\Machine, and refreshing the policy with gpupdate /force, group policy settings started to apply and error event 1096 was history from System event log.

Monday, April 9, 2012

2012 Scripting Games


If you missed the first week, there is one more week left for submitting scripts. Join the fun !

2012 Scripting Games