Difference between revisions of "PowerShell Examples"

Jump to navigation Jump to search
6,150 bytes added ,  13:29, 18 April 2012
Added Depreciated template
(Initial creation)
 
(Added Depreciated template)
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{Depreciated|category=PowerShell}}
== Excel ==
== Excel ==
Basic example, converting an esxisting CSV file into a XLSX file...
Basic example, converting an esxisting CSV file into a XLSX file...
Line 34: Line 36:


=== Formatting ===
=== Formatting ===
{|cellpadding="1" cellspacing="0" border="1"
{|class="vwikitable"
|- style="background-color:#bbddff;"
|-  
! Example                                                        !! Description
! Example                                                        !! Description
|-
|-
Line 302: Line 304:
</source>
</source>


=== Test for NULL ===
In order to be able to test for a NULL value in a set of results from a query, you need to compare against a specific DB NULL value.  Otherwise you'll get an error similar to...
<code> Error: "Cannot convert the "0" value of type "System.Int32" to type "System.DBNull" </code>
So to correctly test, use the following...
<source lang="powershell">
if ([System.DBNull]::Value.Equals($db_query_result)) {
    Write-Host "Result is NULL"
}
</source>
The above was sourced from http://blogs.technet.com/b/industry_insiders/archive/2008/09/15/testing-for-database-null-values-from-powershell.aspx
== Scheduling ==
Script to run a function at a specific interval throughout the day
<source lang="powershell">
$start = Get-Date
# Scheduler stuff...
$DoSingleRun = 0            # Ignore scheduling and just run once
$IntervalMins = 15          # Should fit into an hour exactly
$End = "18:50"              # Time of day that script should cease (should be just after last required run time)
$CheckThrottle = 250        # Idle throttle / time check interval (msec)
# Include library files
. .\lib\Standard.ps1


# Scheduled functions =================================================================================
function Do-Stuff {
    # This is where the business of the script goes
}
function Log-Perf {
    # Keeps track of script resource usage
    Log ("Perf CPU(sec): " + [Math]::Round($proc.cpu, 0) + ", Paged Mem (MB): " + [Math]::Round(($proc.pm/1024), 0) + ", WrkSet Mem (MB): " +  Math]::Round(($proc.ws/1024), 0))
}
# MAIN SCRIPT ====================================================================================
# Initial prep -----------------------------------------------------------------------------------
if ($DoSingleRun) {
    Start-Transcript -Path check-test.log -Append
} else {
    Rename-Item -Path check.log -NewName check-1.log -Force
    Start-Transcript -Path check.log -Append
}
Log "Started script run at $start"
# Get process for this script
$proc = [System.Diagnostics.Process]::GetCurrentProcess()
# Check scheduler variables
if ((60 % $IntervalMins) -ne 0) {
    Log "Interval error - $IntervalMins mins doesn't fit into an hour!"
    Exit
}
try {
    $EndTime = Get-Date $End
} catch {
    Log "Invalid end time: $End hrs"
    Log $_.Exception.GetType().FullName
    Log $_.Exception.Message
    Exit
}
# Set dummy last run time (aligned to nice start time), and next run time
$LastRunTime = Get-Date
$offset = ($IntervalMins + ($LastRunTime.Minute % $IntervalMins))
$LastRunTime = $LastRunTime.AddMinutes(-$offset)
$LastRunTime = $LastRunTime.AddSeconds(-$LastRunTime.Second)
$NextRunTime = $LastRunTime.AddMinutes($IntervalMins)
#Write-Host "Offset is      " $offset
Log ("Last runtime is " + $LastRunTime)
Log ("Next runtime is " + $NextRunTime)
Log ("Script cease at " + $EndTime)
# Do any once-off initialisation here,
#  eg connect to a MySQL database, open an "I'm alive" TCP port, load credentials
# Main loop -------------------------------------------------------------------------------------
if ($DoSingleRun) {
    Log ("Doing single run...")
    Perform-ESX-Check
} else {
    While (1) {
        if ($NextRunTime -lt (Get-Date)) {
            Log-Perf
            Log ("Starting run at " + (Get-Date))
            Do-Stuff
            Log ("Completed run at " + (Get-Date))
            $LastRunTime = $LastRunTime.AddMinutes($IntervalMins)
            $NextRunTime = $LastRunTime.AddMinutes($IntervalMins)
            if ($NextRunTime -lt (Get-Date)) {
                Log "WARNING: Next run is going to be late!"
            }
        }
        if ($EndTime -lt (Get-Date)) {
            Log ("Script ending at " + (Get-Date))
            Break
        }
        Start-Sleep -Milliseconds $CheckThrottle
    }
}
# Do any final once-off completion stuff here
# - EG disconnect from database, send "I'm finished" email
Stop-Transcript
</source>


== SMTP / Email Sending ==
== SMTP / Email Sending ==
Line 351: Line 467:
</source>
</source>


[[Category:PowerShell]]
== SSH Client ==
[[Category:MySQL]]
=== Tamir Gal SharpSSH ===
There are a number of examples of using PowerShell to act as a client to interact with SSH servers, all that I've found using [http://www.tamirgal.com/blog/page/SharpSSH.aspx Tamir Gal's SharpSSH .NET library] - eg [http://poshcode.org/1010 PoSh 1010].  Its a port of a Java implementation and whilst some people have obviously had success in using it, I always seemed to get the following error when trying to write to SSH session with a Vyatta router...
 
# ChannelSession.run
System.IO.IOException: Write end dead
  at Tamir.Streams.PipedInputStream.read()
  at Tamir.Streams.PipedInputStream.read(Byte[] b, Int32 off, Int32 len)
  at Tamir.Streams.PipedInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)
  at Tamir.SharpSsh.java.io.JStream.Read(Byte[] buffer, Int32 offset, Int32 count)
  at Tamir.SharpSsh.jsch.ChannelSession.run()
 
I suspect the ''Write end dead'' fault is caused by the SSH server throwing an error and closing the socket, due to an disliked command.  Which in a way, is fair enough, but its not a particularly graceful way of handling things.
 
=== Renci SSH.NET ===
[http://sshnet.codeplex.com/ Renci SSH.NET] is an ongoing project, still in beta, but already provides a workable solution. Providing both .NET 4.0 and 3.5 libraries (you need 3.5 for PowerShell v2).
 
To get running you need to download the binary DLL file from http://sshnet.codeplex.com/releases/view/72214, and put it in a place where you can load the assembly into your PowerShell session, eg
 
<source lang="powershell">
[void][reflection.assembly]::LoadFrom( (Resolve-Path ".\lib\RenciSSH\Renci.SshNet.dll") )      # DLL file is in \lib\RenciSSH\ below calling script
</source>
 
Create a SSH Client object, and connect...
<source lang="powershell">
$SshClient = New-Object Renci.SshNet.SshClient("ssh-server", 22, "user", "password")
$SshClient.Connect()
</source>
 
Run a command (eg a Unix <code>ifconfig</code> against the server...
<source lang="powershell">
if ($SshClient.IsConnected) {
    $SshCommand = $SshClient.RunCommand("ifconfig")
    $ifconfig = $SshCommand.Result.Split("`n")
}
</source>
 
Clear down...
<source lang="powershell">
$SshCommand.Dispose()
$SshClient.Disconnect()
$SshClient.Dispose()
</source>

Navigation menu