Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Wednesday, April 20, 2011

Scripting Games Beg5


function Get-BasicOSinfo {

<#
.Synopsis
Gets basic Compuer OS Info
.Description
Gets basic OS Info from local or remote machines
.Parameter ComputerName
Name of the Computer (local or remote).

.Example
PS> get-BasicOSInfo -computername MycomputerName
PS> "computername" | get-BasicOSinfo
PS> get-content input.txt | get-BasicOSInfo
PS> import-csv input.csv | get-BasicOSInfo

.Link
about_functions
about_functions_advanced
about_functions_advanced_methods
about_functions_advanced_parameters

.Parameter ComputerName
Computername as a string to query

#>

[CmdletBinding()]
param(
[parameter(Position=0,Mandatory=$true,
ValueFromPipeline=$true,ValueFromPipeLineByPropertyName= $true)]
[String[]]$ComputerName
)
begin { $date = Get-Date -format MM/dd/yy } # Gather current date

process {
# Query WMI of local or remote system
$ComputerSystem = gwmi Win32_Computersystem -Computer $computername
$OperatingSystem = gwmi win32_operatingsystem -ComputerName $computername
$OS = $operatingSystem.caption

$user = $(($computerSystem.username.split("\"))[1])
$computer = $computersystem.caption
$domain = $computersystem.domain

# Populate table with tabs and newline/Carriage Return charaters
# then ouput to file in ascii format.

$result += "User:`t`t $user`r`n"
$result += "Computer:`t $computer`r`n"
$result += "Domain:`t`t $domain`r`n"
$result += "OS:`t`t $OS`r`n"
$result += "User information collected on:`t $date`r`n"
$result += "`r`n"
$result | Out-File result.txt -Encoding ascii

}
}

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!

Tuesday, May 12, 2009

Run Powershell V.1 & 2 on the same machine

Powershell MVP Shay Levy has a really cool article on running Powershell Version 1 and 2 on the same computer using Virtual PC on Windows 7.

A really interesting read. Check it out here.

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.



Wednesday, November 12, 2008

A MS SQL Form from PS

My custom form for quick MSSQL Queries via PS.























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 {~}



Wednesday, August 13, 2008

Wednesday, August 6, 2008

Foreach vs Foreach-object

Powershell MVP Brandon Shell, has an excellent article on the differences of Foreach and the Foreach-object. You can find it here.

Very good read.

Wednesday, July 23, 2008

Create Assembly and Import into PowerShell

I don't see much documentation on how to create and import your own assembly (DLL) file into PoSH so I thought I would shed some light into how I've done this. So why would you do this anyway? Well if you've created your own custom .Net Class or you want to create an assembly file from code somebody has shared and import that into PowerShell to use.

I'm not a developer so feel free to correct me if I state some untruths here. My examples are with Visual Studio 2005.

First, create your assembly (DLL) file. This is just a Fibonacci C# series example that I've seen on the web. Note: the class and methods if you wish to use them in PS must be public!


   1:  using System;
   2:  
   3:  public class Fib
   4:  {
   5:      Decimal current;
   6:      Decimal last;
   7:      public Fib()
   8:      {
   9:          current = 1;
  10:          last = 0;
  11:      }
  12:      private Fib(Decimal last, Decimal secondToLast)
  13:      {
  14:          current = last + secondToLast;
  15:          this.last = last;
  16:      }
  17:      public Fib GetNext()
  18:      {
  19:          return new Fib(current, last);
  20:      }
  21:      public Decimal Value
  22:      {
  23:          get { return current; }
  24:      }
  25:  }

Build the Assembly.



This will create your DLL file, for me it was located in my ~\Visual Studio 2005\Projects\pstest\pstest\bin\Release folder
Although not needed, I moved the file to my desktop to I can reach it faster.

After the assembly has been created your ready to import it into PS. With V.1 of PS you need to use reflection to import the assembly. In v2 you can use the new cmdlet Add-Type. I don't have V2 so I'll list the reflection method. Remember when importing the assembly you must use the entire path, relative paths will throw an error.

_=\|/=_PoSH_=\|/=_ $assemblyFile = Join-Path $home "\desktop\pstest.dll"
_=\|/=_PoSH_=\|/=_ [System.Reflection.Assembly]::LoadFile($assemblyFile)

GAC Version Location
--- ------- --------
False v2.0.50727 C:\Users\jdelatorre\Desktop\pstest.dll


_=\|/=_PoSH_=\|/=_ $fib = New-Object fib
_=\|/=_PoSH_=\|/=_ for ($i = 0;$i -lt 10;$i++) {
>> $fib = $fib.GetNext()
>> $fib.Value
>> }
>>
1
2
3
5
8
13
21
34
55
89
_=\|/=_PoSH_=\|/=_

As you can see I create the object FIB using the New-Object Cmdlet. Then I loop through the Fibonacci numbers using a "for" loop showing the use of the Class's public methods and properties.

Tuesday, July 22, 2008

Speed up V.1 PowerShell Startup Time

As some of you may know PS start up is pretty slow, so I try keep the console open at all times through out my day. That still doesn't solve the speed issue. Yet, there is hope!! There was a post on the Powershell Team Blog a while ago on speeding up the start up time for PS version 1.0
This is the script that they posted to help and boy it sure did. Remember you have to run the command/console as Administrator! Note: This is not needed in V2 of the CTP, as this bug has been fixed in this version.

   1:  Set-Alias ngen @(
   2:  dir (join-path ${env:\windir} "Microsoft.NET\Framework") ngen.exe -recurse |
   3:  sort -descending lastwritetime
   4:  )[0].fullName
   5:  [appdomain]::currentdomain.getassemblies() | %{ngen $_.location}


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!!

Tuesday, June 17, 2008

Help file of the day

About a month ago there was a interesting post on Mark Minasi's forum from Xenophane. It basically was about Don Jones recommendation for reading one Powershell help file a day to really get a solid foundation of how the cmdlets, providers, etc work.


My function, pretty different from Xenophane's. I put this in my profile so when PS starts I get a help file with it's full description with examples, and in pretty Green font.

   1:  function new-help {
   2:      # Create array of all help topics excluding the Alias topic
   3:      $helptopics = get-help * | ? { $_.Category -ne "alias" }
   4:  
   5:      # Create Random object for a random seed
   6:      $random = new System.Random
   7:  
   8:      # Get Random Help Topic name from array
   9:      $name = ($helptopics)[$random.Next(0, $helptopics.Count)].name
  10:  
  11:      # Save help file into a variable w/ Out-string
  12:      $helptopic = get-help $name -Full | Out-String 
  13:  
  14:      # Print the random Help file
  15:      write-host "Help file of the day" -fore green 
  16:      write-host $helpTopic -fore green
  17:      write-host "End of Help Tip of the day" -fore green
  18:  }

With PS V2 this can be really simplified with the Get-Random cmdlet.

Save the above function into your profile script then call it. Remember, you can't call a function before it's been defined.

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