Posts RSS Comments RSS 127 Posts and 199 Comments till now

Test-Port (kinda like portqry without verbose output)

We had a little dicussion on www.powershelllive.com forums about the most efficient way to Test a machine before trying a WMI query against it (as it has a log timeout.) My first suggestion was to use a ping (WMI style) but Jeff from http://blog.sapien.com brought up a valid point… what if ICMP is NOT Allowed…

Enter Test-Port. This nifty little script uses the TCPClient Class to test connectivity. Stay tuned as I am planning some mods.

Test-Port
- Takes parameter $srv for Server Name
- Takes Parameter for Port, Defaults to 135 for RPC mapper.
- Takes Timeout.. defaults to 3000 (miliseconds)
- If it cannot connect within timeout… Returns $false
- If it gets exception connecting to port… Returns $false
- If it connects… Returns $True

function Test-Port{
    Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)
    $ErrorActionPreference = "SilentlyContinue"
    $tcpclient = new-Object system.Net.Sockets.TcpClient
    $iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
    $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
    if(!$wait)
    {
        $tcpclient.Close()
        if($verbose){Write-Host "Connection Timeout"}
        Return $false
    }
    else
    {
        $error.Clear()
        $tcpclient.EndConnect($iar) | out-Null
        if($error[0]){if($verbose){write-host $error[0]};$failed = $true}
        $tcpclient.Close()
    }
    if($failed){return $false}else{return $true}
}

Run-Command.ps1 : Run External Commands with Power!

I was working late tonight and we had to run a bunch of third party EXEs and such. We do this a good bit so I can’t always avoid calling external executables and I also find psexec.exe much easier than any powershell way to run remote commands. That said I find myself constantly writing this.

$servers = Get-Content $file
foreach($server in $servers)
{
   Do Something Here Like
   psexec \\$server mycmd.exe param1
}

I decided to write a script call Run-Command.ps1.
This will take three parameters
- File (list of servers to process)
- Cmd (Command to run with %S% where you want the server name to be replaced)
- Check (just shows what command would run)
- Will also take Piped Input

Example:
PS> .\Run-Command.ps1 -file c:\serverlist.txt -cmd “psexec \\%S% mycmd.exe Hello World” -check

Run-Command.ps1

Param($file,$cmd,[switch]$whatif,[switch]$verbose)
Begin{
    function Ping-Server {
        Param([string]$srv)
        $pingresult = Get-WmiObject win32_pingstatus -f "address=’$srv’"
        if($pingresult.statuscode -eq 0) {$true} else {$false}
    }
    $servers = @()
}
Process{
    if($_)
    {
        if($_.ServerName){$servers += $_.ServerName}
        else{$servers += $_}
    }
}
End{
    if($file){Get-Content $file | %{$servers += $_}}
    foreach($server in $servers)
    {
        if(ping-server $server)
        {
            if($verbose){Write-Host "+ Processing Server $Server"}
            $mycmd = $cmd -replace "\%S\%",$Server
            if($whatif){Write-Host "  - WOULD RUN $mycmd"}
            else{if($verbose){Write-Host "  - Running $mycmd"};invoke-Expression $mycmd}
        }
        else
        {
            Write-Host "+ $Server FAILED PING" -foregroundcolor RED
        }
    }
}

C# to PowerShell Translation Thought Process

A gentleman on the powershell news group the other day was asking about executing SQL stored procedures and I provided him with example that I had posted earlier in my blog (Click Here) While I’m not sure my answer was exactly what he was looking for he was a little curious as to how I went about translating the original C# code. To be clear I am not a coder nor do I truly know C#, but I know enough to translate. Anyway, I decided this would be a good idea for a post

So… Here we GO!

First… I used this as the C# example
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx

I will show you my thought process by section I will include my comments and after I will post Both code Sections

This was fairly simple. In C# you have the ability to take namespace shortcuts by using ‘using ;’ In PowerShell we dont as of yet have that ability so I had to figure out what class SqlConnection was. A MSDN query returned System.Data.SqlClient.SqlConnection. The resulting PowerShell code is

The C# Code:

// Setup
conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

The Powershell Code:

$srv = "srv1"
$db = "Northwind"
$conn = new-Object System.Data.SqlClient.SqlConnection("Server=$srv;DataBase=$db;IntegratedSecurity=SSPI")
$conn.Open() | out-null # The out-null is because the method returns a value and I dont want that output

Again… I had to find out what SqlCommand was referencing so… back to MSDN… System.Data.SqlClient.SqlCommand. BTW… I think I should take time now to tell you it is a REALLY GOOD idea to get use to the idea of constructors (how the object should be created) and how to use MSDN to determine the correct way to create an instance of the class/object. It really helps to know what a class is expecting. In this example its good to know the constructor is wanting a string of the SP and A connection OBJECT to use.

The C# Code:

// 1.  create a command object identifying
//     the stored procedure
SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

Here is the PowerShell Code:

$cmd = new-Object System.Data.SqlClient.SqlCommand("CustOrderHist", $conn)

Here was the tricky part (at least sorta.) From the C# code its not clear if the CommandType.StoredProcedure is a property and it turns out its not. It is an enumeration. It took me a few clicks to figure it out. The first clue was when looking for CommandType… I got an enum and it turns out the valid options was StoredProcedure, TableDirect, or Text (MSDN LINK) Clearly this was an enum, but I was a little unsure how do to enums in powershell. I found this blog by /\/\0\/\/ that helped a lot (/\/\o\/\/ Link)

The C# Code:

// 2. set the command object so it knows
//    to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

I ended up with this Powershell Line:

$cmd.CommandType = [System.Data.CommandType]‘StoredProcedure’

This was fairly simple as well… Just had to drop the new sqlparameter because strongly typing was not required. Again the out-null was because the method returns data I did not want as well as set the parameters.

The C# Code:

// 3. add parameter to command, which
//    will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

The PowerShell Code:

$cmd.Parameters.Add("@CustomerID","ANATR") | out-Null

These two parts are really just the excution of the the previous code. I think the only difference is the way PowerShell Writes output

The C# Code:

// execute the command
rdr = cmd.ExecuteReader();

// iterate through results, printing each to console
while (rdr.Read())
{
 Console.WriteLine(
 "Product: {0,-35} Total: {1,2}",
 rdr["ProductName"],
 rdr["Total"]);
}

The Powershell Code:

$rdr = $cmd.ExecuteReader()
While($rdr.Read()){
    Write-Host "Product Name: " $rdr[‘ProductName’]
    Write-Host "Total: " $rdr[‘Total’]
}

Here is the Complete PowerShell Code.

$srv = "srv1"
$db = "Northwind"
$conn = new-Object System.Data.SqlClient.SqlConnection("Server=$srv1;DataBase=$db;Integrated Security=SSPI")
$conn.Open() | out-null
$cmd = new-Object System.Data.SqlClient.SqlCommand("CustOrderHist", $conn)
$cmd.CommandType = [System.Data.CommandType]‘StoredProcedure’
$cmd.Parameters.Add("@CustomerID","ANATR") | out-Null
$rdr = $cmd.ExecuteReader()
While($rdr.Read()){
    Write-Host "Product Name: " $rdr[‘ProductName’]
    Write-Host "Total: " $rdr[‘Total’]
}
$conn.Close()
$rdr.Close()

UPDATED!!! Get-Uptime (The Custom Object extravaganza!!!)

One of the most wonderful things about PowerShell is the ability to pass objects down the Pipe for further processing. In my first version of Get-Uptime I did not utilize this because I wanted to show what a huge difference it makes. I wanted to get this out pretty quick so I didn’t add the prettiness that I had in my first version, but it is easy enough to add.

Here is the new Code. After the code I give some examples of how to use it.

Function Get-Uptime{
    Param([string]$server)
    Begin {
        function PingServer {
            Param([string]$srv)
            $pingresult = Get-WmiObject win32_pingstatus -f "address=’$srv’"
            if($pingresult.statuscode -eq 0) {$true} else {$false}
        }
        function myUptime {
            param([string]$srv)
            $os = Get-WmiObject Win32_OperatingSystem -ComputerName $srv
            $uptime = $os.LastBootUpTime
            return $uptime
        }
        function ConvertDate {
            param([string]$date,[string]$srv)
            $year = $date.substring(0,4)
            $Month = $date.Substring(4,2)
            $day = $date.Substring(6,2)
            $hour = $date.Substring(8,2)
            $min = $date.Substring(10,2)
            $sec = $date.Substring(12,2)
            $RebootTime = new-Object System.DateTime($year,$month,$day,$hour,$min,$sec)
            $now = [System.DateTime]::Now
            $uptime = $now.Subtract($RebootTime)
            $uptimeval = "$($uptime.days) days, $($uptime.Hours) hours, $($uptime.Minutes) minutes, $($uptime.seconds) seconds"
            $lastReboot = $rebootTime.toString()
            $sObject = new-Object -typename System.Object
            $sObject | add-Member -memberType noteProperty -name ServerName -Value $srv
            $sObject | add-Member -memberType noteProperty -name Days -Value $uptime.days
            $sObject | add-Member -memberType noteProperty -name Hours -Value $uptime.Hours
            $sObject | add-Member -memberType noteProperty -name Minutes -Value $uptime.Minutes
            $sObject | add-Member -memberType noteProperty -name Seconds -Value $uptime.seconds
            $sObject | add-Member -memberType noteProperty -name uptime -Value $uptimeval
            $sObject | add-Member -memberType noteProperty -name LastReboot -Value $rebootTime.ToUniversalTime()
            $sObject | add-Member -memberType noteProperty -name LastRebootUtc -Value $rebootTime.ToFileTimeUtc()
            write-Output $sObject
        }
        Write-Host
        $process = @()
        $objCollection = @()
    }
    Process {
        if($_){
            if($_.ServerName ){
                $process += $_.ServerName
            }
            else{
                $process += $_
            }
        }
    }
    End {
        if($Server){$process += $server}
        $i = 1
        foreach ($Server in $process){
            write-progress $Server "Total Progress->" -percentcomplete ($i/$process.length*100)
            if(PingServer $server){
                $result = myUptime $server
                $srvObject = ConvertDate $result $server
                $objCollection += $srvObject
            }
            else {
                Write-Host "Server [$server] not Pingable" -foregroundcolor red
            }
            $i = $i+1
        }
        Write-Output $objCollection
        Write-Host
    }
}

Examples:

This get uptime on a Single Server

get-uptime server | %{$_.uptime}

This gets all servers up for more than 30 days

$sl | Get-Uptime | ?{$_.Days -gt 30} | %{write-host "$($_.ServerName) :: $($_.uptime)"}

This Displays the Last Reboot Time of a list of servers.

$sl | get-uptime | %{Write-Host "Server $($_.ServerName) rebooted on $($_.LastReboot)"}

The part of this I want to focus on is this

$sObject = new-Object -typename System.Object
 $sObject | add-Member -memberType noteProperty -name ServerName -Value $srv
 $sObject | add-Member -memberType noteProperty -name Days -Value $uptime.days
 $sObject | add-Member -memberType noteProperty -name Hours -Value $uptime.Hours
 $sObject | add-Member -memberType noteProperty -name Minutes -Value $uptime.Minutes
 $sObject | add-Member -memberType noteProperty -name Seconds -Value $uptime.seconds
 $sObject | add-Member -memberType noteProperty -name uptime -Value $uptimeval
 $sObject | add-Member -memberType noteProperty -name LastReboot -Value $rebootTime.ToUniversalTime()
 $sObject | add-Member -memberType noteProperty -name LastRebootUtc -Value $rebootTime.ToFileTimeUtc()

This is where I define my custom object. There are numerous ways to do this, but I chose this way. Notice the use of add-member cmdlets… It is extremely powerfull and extremely easy to use.

Basically what I do is create a Generic Object $sObject. Add some noteProperties and populate them. Very simple, but as you can very “POWER”ful.

Lee Holms has some excelent information on Custom Objects here:
http://www.leeholmes.com/blog/AddCustomMethodsAndPropertiesToTypesInPowerShell.aspx

I hope you enjoyed this new version… I currently actually keep both versions in my functions.ps1 file that I load in my profile. One as Get-Uptime and one as Get-UptimeExt. I get pretty and Smart :)