Difference between revisions of "PowerShell Examples"

Jump to navigation Jump to search
2,829 bytes added ,  13:29, 18 April 2012
Added Depreciated template
(Added "Scheduling" script)
(Added Depreciated template)
 
(4 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>


== SMTP / Email Sending ==
So to correctly test, use the following...
http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx#
 
Emails can be send very simply if no attachment is needed....
 
<source lang="powershell">
<source lang="powershell">
$smtp = New-Object Net.Mail.SmtpClient -arg $smtpServer
if ([System.DBNull]::Value.Equals($db_query_result)) {
$smtp.Send($emailFrom,$emailRcpt,$emailSubject,$msgBody)
     Write-Host "Result is NULL"
</source>
}
 
* '''<code> $emailRcpt </code>''' - Multiple email addresses need to be comma seperated
 
=== With Attachments ===
<source lang="powershell">
$smtp = New-Object Net.Mail.SmtpClient -arg $smtpServer
$msg = New-Object Net.Mail.MailMessage
$attach = New-Object Net.Mail.Attachment($OutputFile)          # See note below
   
$msg.From = $emailFrom
$msg.To.Add($emailRcpt)
$msg.Subject = $emailSubject
$msg.Body = $msgBody
$msg.Attachments.Add($attach)
      
$smtp.Send($msg)
$attach.Dispose()
</source>
 
* '''<code> $OutputFile </code>''' - Will normally need to be a full path as the script needn't be executing where your script is, assuming attachment is in same directory as script use the following...
** <code>((Get-Location -PSProvider FileSystem).ProviderPath) + "\" + $OutputFile </code>
 
=== With SMTP Authentication ===
As above, but additionally create a credential object and link it to the SMTP Client object, so...
<source lang="powershell">
$cred = new-object System.net.networkCredential
$cred.domain = "the domain you want"
$cred.userName = "username"
$cred.password = "password"
$smtp.credentials = $cred
</source>
 
=== With Embedded HTML ===
As above, but you need to set the <code> IsBodyHTML </code> option for the message, so...
<source lang="powershell">
$msg.IsBodyHTML = $true
</source>
</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 ==
== Scheduling ==
Script to run a function at a specific interval throughout the day
Script to run a function at a specific interval throughout the day
<source lang=powershell">
<source lang="powershell">
$start = Get-Date
$start = Get-Date


Line 454: Line 420:
</source>
</source>


[[Category:PowerShell]]
== SMTP / Email Sending ==
[[Category:MySQL]]
http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx#
 
Emails can be send very simply if no attachment is needed....
 
<source lang="powershell">
$smtp = New-Object Net.Mail.SmtpClient -arg $smtpServer
$smtp.Send($emailFrom,$emailRcpt,$emailSubject,$msgBody)
</source>
 
* '''<code> $emailRcpt </code>''' - Multiple email addresses need to be comma seperated
 
=== With Attachments ===
<source lang="powershell">
$smtp = New-Object Net.Mail.SmtpClient -arg $smtpServer
$msg = New-Object Net.Mail.MailMessage
$attach = New-Object Net.Mail.Attachment($OutputFile)          # See note below
   
$msg.From = $emailFrom
$msg.To.Add($emailRcpt)
$msg.Subject = $emailSubject
$msg.Body = $msgBody
$msg.Attachments.Add($attach)
   
$smtp.Send($msg)
$attach.Dispose()
</source>
 
* '''<code> $OutputFile </code>''' - Will normally need to be a full path as the script needn't be executing where your script is, assuming attachment is in same directory as script use the following...
** <code>((Get-Location -PSProvider FileSystem).ProviderPath) + "\" + $OutputFile </code>
 
=== With SMTP Authentication ===
As above, but additionally create a credential object and link it to the SMTP Client object, so...
<source lang="powershell">
$cred = new-object System.net.networkCredential
$cred.domain = "the domain you want"
$cred.userName = "username"
$cred.password = "password"
$smtp.credentials = $cred
</source>
 
=== With Embedded HTML ===
As above, but you need to set the <code> IsBodyHTML </code> option for the message, so...
<source lang="powershell">
$msg.IsBodyHTML = $true
</source>
 
== SSH Client ==
=== 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