Showing posts with label Admin Tools. Show all posts
Showing posts with label Admin Tools. Show all posts

Monday, June 6, 2011

Find a logged on users computer name

One thing that is hard to track down without 3rd party tools or something like SCCM is finding the computer name of a domain user that he/she is using or last used. And those that do even just a little help desk support get a sour taste in their mouth when they begin to ask the question, "Do you know what your computer name is"?

Well, with a little work up front you should be able to get this info a bit easier without asking the user for any information. What you have to enable is pretty simple:

Enabling 'Audit Account Logon Events' for your domain controller policy so that all your domain controllers will audit Successful, or failure, user logon attempts. Your can read more about this here. Once you have auditing enabled you might want to increase the size of your security event log size because the log begins to fill up very quickly, especially if your auditing more then just the Account logon events.

Once you have enabled Account Logon events all successful user requests for Kerberos tickets will be logged in the Security Log at event id: 4768. Now all we have to do is query the DC for this event and parse the event for the username, computer name and time it was requested. Now I know there are problems with this method. Such as, what if you have hundreds of domain controllers, how would you know what DC authenticated that user? Or that user has been logged into several other computers? Well one of those problems can be resolved if you have event log forwarding for this event on your domain to a centralized server, this can only be used if you have Windows Server 2008 however. Anyhow, here is the script.

function Get-UserComputerName {
<# .SYNOPSIS Searches a specified Domain Controller for the computername of a logged on user. .DESCRIPTION Queries a DC for Event ID 4768 (Kerberos authentication ticket,TGT) request from the servers Security event log. .PARAMETER UserName SamAccount name of the user to search for .EXAMPLE PS> .\Get-UserComputerName -UserName "John_Doe" -Server "My_DC"
Searches for user John_Doe on Domain Controller My_DC
.EXAMPLE
PS> .\Get-UserComputerName -Username "John_Doe"
Searches for user John_Doe using the logged on server name for the current user
running the script.
.EXAMPLE
PS> .\Get-UserComputerName
Searches the current user on the logged on server name
#>

param([string]$username = $env:username,[string]$server = $env:logonserver)
$ErrorActionPreference = "silentlycontinue"
if ($server.StartsWith("\\")) {$server = $server.Remove(0,2)}

$events = Get-WinEvent -ComputerName $server -MaxEvents 5 -FilterHashTable @{logname="security";id=4768;data=$username}
# Check if error has been raised from EventLog Query.
if (!$?) {Write-Warning "No successful logon events were found on Server: $server for Username: $username"
break
}

foreach ($event in $events) {
$myObject = New-Object -TypeName system.Object
[string]$Computer = $event.message.split("`n") | Select-String "Client Address"
$addressLine = $computer.replace("Client Address:",'')
$addressLine = $addressLine.trim()
if ($addressLine.startswith("::ffff:")) { $address = $addressLine.replace("::ffff:",'') }
$DNSResult = [system.Net.Dns]::Resolve($address)
$ComputerName = $DNSResult.HostName
$timeStamp = $event.timecreated

$myObject | Add-Member -MemberType noteproperty -Name AuthDC -Value $server
$myObject | Add-Member -MemberType noteproperty -Name TimeStamp -Value $timeStamp
$myObject | Add-Member -MemberType noteproperty -Name UserName -Value $username
$myObject | Add-Member -MemberType noteproperty -Name IPAddress -Value $address
$myObject | Add-Member -MemberType noteproperty -Name ComputerName -Value $computerName
$myObject
}
}

Wednesday, May 20, 2009

PSCX 1.2 Beta Released

PowerShell Community Extensions 1.2 have been released in Beta form. You can find it here.

http://www.nivot.org/2009/05/15/Pscx12BetaReleased.aspx

If you an unfamiliar with the PSCX tools it's WELL worth the look. Unbelievably helpful stuff!

Thursday, May 7, 2009

PowerShell Plus 3.0 now released!

If you have a PowerShell editor then you probably have heard of Idera's product PowerShell Plus. If you havent you can find more info here. They also offer tools for the SQL and Sharepoint Admin so its worth the look if your one of those guys! 8)

I have been using PS+ version 2 for quite some time now and I absolutely love it. IMHO it is hands down the best PS text editor and console application for PS. It has an excellent debugger, Intellisense code completion, variable previewer, and other visual options to fit pretty much anyones needs or wants. But PS+ isn't just for PS files although that is it's main function. PS+ also has language support for XML, HTML, C#, VB.Net, Vbscript, and the newly PowerShell V2 PowerShell Modules.

Several improvement have been included in the V3 release such as support for VBscript and Windows 64bit versions (If your going to run PS+ on a 64bit machine vbscript support will not be available as the PS+ dependancy only works with a 32bit dll "tlbinf32.dll"). You can now download and upload scripts directly from Powershell.com or Poshcode.org using the editor. Very cool! The most in your face upgrade the new Intellisense Help window.



Here you can see without using Get-help the data type for the given parameter and whether it is an optional parameter, a switch parameter (indicated by the 'S' or number of the left of parameter name). What I like the most about this is it gives you the same info for that given parameter that you would receive from Get-help, saving you tons of time in the long run. In addition you can click on the bottom available links in the help windows to either do a google search on your cmdlet or paramater or if available visit MSDN directly.

AWESOME!!

Great work Tobias and the rest of the people at Idera.

Wednesday, March 18, 2009

Random Password Generator

Here I'm using a VERY simple function to generate a random password. The function is mainly built around the use of the new V2 CTP cmdlet called Get-Random. This cmdlet takes all the headache out of using the code like this:

$r = New-Object system.Random
$r.next(1,100)

I know, it's not a lot of typing but with the Get-Random cmdlet really is much easier to generate random numbers, plus it has the ability of choosing random items from any given array from the pipeline.

This code is VERY simple compared to some of those password scripts out there.

function Get-RandomPassword {
param([int]$length = 4)
@(1..$length | % { [char](Get-Random -Minimum 48 -Maximum 122) }) -join ''
}

Here, I'm simply grabbing a set number of random ascii characters and using the new join operator to join the characters to spit out the random password.

All that is needed now is to add this to your profile or to a module; import and your ready to start pumping passwords through. Pretty easy eh!

I will post later with the Advanced Function version of this so it can be used in the pipeline and with built-in help features.

Thursday, March 5, 2009

I've been up for days!!

When was that machine last rebooted?


function Get-Uptime {
param([string]$computer = $env:computername)
$computer = $computer.toupper()
if (Test-Connection $computer -Count 1 -ea silentlycontinue) {
    $WMITimeString = (gwmi -Query "Select lastbootuptime from win32_operatingsystem" -computer $computer).lastbootuptime
    $bootTime = ([wmi]'').ConvertToDateTime($WMITimeString)
    $formattedTime = (Get-Date $bootTime).datetime
    Write-Host -fore green -Background black "Computer $computer has been up since:`n`n`t $formattedTime"
    }else {Write-Host -fore red -Background black "Computer $computer is not online."}
}

The script will check the local machine if no parameter is specified.

Tuesday, February 10, 2009

The new Ping from PS CTP3

Lately, because of my heavy work load I've been unable to write much about the CTP3 release. However there has been a lot of writings out there to more then quench your PoSh thirst. I'll try to do my part and get back on track with my post. 8)

There are a lot of things added to the CTP3 of Powershell, which I'll try write about over the next few weeks. Today I'll talk about one of the new cmdlets that really hasn't received much attention. I feel it's probably one of the most useful as a Sys Admin. The 'Test-Connection' cmdlet. It has some really useful parameters that can save you time before you try to execute some commands on that workstation that is powered off, or ping from a computer that is not your own.

The first useful parameter for the Test-Connection cmdlet is 'Count'. Not too surprising, what the count parameter does is determine how many ICMP requests to send to the destination address. Very useful if you want to only send 1 or 2 requests to the computer to check it's alive. If the count parameter is not specified a default of 4 request are sent.


Sjdelatorre@JDELATORRE {~} Test-Connection jdelatorrevm -Count 10

Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
JDELATORRE jdelatorrevm 192.168.249.82 32 5
JDELATORRE jdelatorrevm 192.168.249.82 32 81
JDELATORRE jdelatorrevm 192.168.249.82 32 1
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 22
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 4


Sjdelatorre@JDELATORRE {~}


The 'Delay' parameter is another very useful parameter to cut down on the amount of traffic sent over the wire. I use this when rebooting a server and checking to see when it's back up, but instead of consistently pinging the server every second as with Ping.exe -t, you can specify how far apart you want those request. By default the delay is 1 second.

Here I'm pinging my virtual machine 4 times with 10 seconds between each ping request.


Sjdelatorre@JDELATORRE {~} Test-Connection jdelatorrevm -Delay 10

Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 0
JDELATORRE jdelatorrevm 192.168.249.82 32 0


Sjdelatorre@JDELATORRE {~}


Probably the most interesting and sometimes most helpful is the 'Source' parameter. With the source parameter you can specify where your ping request originate from. So it's possible to test the connection speeds to other parts of your network from a server when typing the command at your computer. Here, I'm pinging my laptop but the requests are coming from my VM.


Sjdelatorre@JDELATORRE {~} Test-Connection -Source jdelatorrevm -Destination jdelatorre

Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
JDELATORREVM jdelatorre 192.168.249.54 192.168.249.54 32 0
JDELATORREVM jdelatorre 192.168.249.54 192.168.249.54 32 0
JDELATORREVM jdelatorre 192.168.249.54 192.168.249.54 32 0
JDELATORREVM jdelatorre 192.168.249.54 192.168.249.54 32 0


Sjdelatorre@JDELATORRE {~}

Notice the Source column.


There's quite a bit more to the Test-Connection cmdlet than what I've posted here, such as:

  • AsJob
  • Authentication
  • BufferSize
  • Credential
  • Impersonation
  • ThrottleLimit
  • TimeToLive
I've also created an alias to test-connection called 'ping' with the following command inside of my profile.

set-alias -name ping -value test-connection

So now you can call the Test-Connection cmdlet with just ping

ping jdelatorrevm

As a note. The data that is sent/returned is plain ol' WMI.



Thursday, November 6, 2008

PrimalForms and Lee Holmes Connect to Script

If you've used Lee Holmes' (a developer on the Windows PowerShell team) Connect to PS script you'll know it's pretty useful when connecting to a remote port from the PS console.

So with the recent release of Sapien's new free tool, PrimalForms, this gave me an excuse to convert Lee's great script to a GUI interface. PrimalForms did an awesome job in creating the GUI skeleton, so all I had to do was tie everything together.

Thanks goes out to Lee and the people at Sapien!!





















Monday, November 3, 2008

PrimalScript Releases Free WinForms Tool!

The good people at Sapien have released their free WinForms tool for Powershell today.

You can find it here.

Once I have some time I'll post back on some tips or maybe a WinForm Script of my own. 8)

Thursday, October 16, 2008

Idera PowerShell Plus WMI Intellisense Fix

I was having a problem with Idera's PowerShell Plus intellisense with WMI Classes. Only a few Win32 Classes would be recognized. In order to rebuild the WMI classes and have them recached into PowerShell plus you have to do a few things.

  • When the splash screen of PS+ starts be sure to press the right 'Shift' key. Pressing the left 'Shift' key wouldn't work for me.
  • Check the box to 'Delete cached WMI info'. This check box tells PS+ to rebuild the WMI Class Intellisense, similar to what happens when you first install PS+
  • After PS+ starts, the intellisense works as expected.


Custom IP Object

I recently needed a function that would get the 3rd octet from a group of computers to determine what subnet that computer was on. (Class C)

I had a VBScript that could do this but didn't have anything in PoSh. I decided the best way to do this was to create a custom object to easily get to the octet I needed. Doing it with a PS object provides the ability to select which octet you wanted back. Here is the function.


   1:  function get-ip {
   2:      param ([string]$computer = '.')
   3:      if ($computer -eq '.') {$computer = $env:computername}
   4:      
   5:      # Create custom object
   6:      $objIP = New-Object -typeName 'psobject'
   7:      
   8:      # Connect to WMI and retrieve IP from NetworkAdapterConfiguration Class
   9:      [string]$IP = (gwmi win32_networkadapterconfiguration -computerName $computer | ? { $_.IPEnabled -eq $true }).IPAddress
  10:      
  11:      # Split on the '.' to get each octet
  12:      $octets = $IP.split(".")
  13:  
  14:      # Add octets,ip and computername to the custom object
  15:      Add-Member -inputObject $objIP -memberType 'Noteproperty' -name "1stOct" -value $octets[0]
  16:      Add-Member -inputObject $objIP -memberType 'Noteproperty' -name "2ndOct" -value $octets[1]
  17:      Add-Member -inputObject $objIP -memberType 'Noteproperty' -name "3rdOct" -value $octets[2]
  18:      Add-Member -inputObject $objIP -memberType 'Noteproperty' -name "4thOct" -value $octets[3]
  19:      Add-Member -inputObject $objIP -memberType 'Noteproperty' -name "FullIPv4" -value $ip
  20:      Add-Member -inputObject $objIP -memberType 'Noteproperty' -name "ComputerName" -value $computer
  21:  
  22:      return $objIP
  23:  }


So now you can get whatever octet by using select-object. The function can take an argument named Computer so you can retrieve remote computer addresses/octets as well.


Sjdelatorre@JDELATORRE {~} get-ip

1stOct : 192
2ndOct : 168
3rdOct : 251
4thOct : 46
FullIPv4 : 192.168.251.46
ComputerName : JDELATORRE

Sjdelatorre@JDELATORRE {~} get-ip | select 3rdoct

3rdOct
------
251

Sjdelatorre@JDELATORRE {~} get-ip | select 3rdoct,fullipv4,computername

3rdOct FullIPv4 ComputerName
------ -------- ------------
251 192.168.251.46 JDELATORRE

Sjdelatorre@JDELATORRE {~} get-ip -computer jdelatorreVPC | select 3rdoct,fullipv4,computername

3rdOct FullIPv4 ComputerName
------ -------- ------------
251 192.168.251.67 jdelatorreVPC

Sjdelatorre@JDELATORRE {~}



Monday, June 23, 2008

Get FSMO Roles with PowerShell

The other day I needed to see what servers held which FSMO roles. I know there are many ways to get to this information. The easiest that I know of is using the NetDom resource kit utility.

netdom.exe query fsmo

I however wanted to see if I could use only .NET and not totally rely on any other tools. This was more of a challenge than anything else. I found several ways in .NET to get this info but I settled on this because it seemed the easiest way. If you know of an easier or more efficient way let me know.

   1:  $DCs = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).DomainControllers
   2:  $DCs | % { if ($_.Roles -ne '') {
   3:          "Server $_ has roles:"
   4:          ""
   5:          foreach ($role in $_.roles) {
   6:              $role.tostring().padleft($role.tostring().length + 10)
   7:          }
   8:          ""
   9:      }
  10:  }

The script is not as fast as NetDom, about 1 sec slower in my environment, but it depends only on .net.

Friday, June 20, 2008

Another Great GPO Cmdlet

Darren and the people at SDM software have recently release another AWESOME cmdlet called Group Policy Health. Key features it provides are:

  • Returns "green or red" for each host
  • Can report against a single host, an OU or a domain
  • Provides detailed information about what GPOs were processed, how long processing took and what failed as well as much more detail
  • Provides either object-based or XML output for flexible reporting
  • Leverages PowerShell features for incorporation into existing automation scenarios
A nice intro to the cmdlet can be seen here.

Unfortunately this cmdlet is not part of the excellent freeware PS cmdlets Darren gives out but its only $75 bones. I'm gonna have to try to sell this buy to my boss. Thanks again Darren, excellent work as always!!

Friday, June 13, 2008

Sysinternals Online

If your a fan of the SysInternal tools, you'll love that Microsoft now has released all of them online and readily available with just a web connection. If you haven't used any of the sysinternal tools you really should take a look at them, even if your not an admin user. The tools really are great and best of all they are all FREE!!!

You can get access to them from any computer with a internet connection. Just enter http://live.sysinternals.com/ into any browser and BAM!




Or you can paste this UNC link in to Windows Explorer and BAM!!

\\live.sysinternals.com\tools




Or if your a Console Rat and want it in PowerShell you can type this command and BAM!
You then could do a LS or Dir and see all the tools, copy them out, use them directly, etc.

cd \\live.sysinternals.com\tools
\\live.sysinternals.com\tools
pwd

Path
----
Microsoft.PowerShell.Core\FileSystem::\\live.sysinternals.com\tools


Or even build a Function or do what I did and add a new PS Drive with this command and put it in your profile so you have this drive every time you start PS.

New-PSDrive -Name SYSINT -PSProvider filesystem -Root \\live.sysinternals.com\tools > $null