Post from October, 2009

Subversion 1.6.6 released

Monday, 26. October 2009 14:01

SVN Quick ReferenceSubversion 1.6.6 was released on 21-Oct-2009. It is a maintenance release containing the latest bugfixes to the 1.6.x line. See official release announcement

(Subversion (shortened form: svn) is a highly popular open source version control system for software developers. If you want to learn more about svn read the subversion book. A popular svn client for Windows is TortoiseSVN.)

Category:Utilities | Comment (0) | Author: Frank-Peter

How To Send Email With PowerShell?

Saturday, 24. October 2009 7:40

The PowerShell code below shows how to send an email message via the SMTP protocol.

Note that you can add multiple recipient email addresses.

param(
	[string[]]$To = $(Read-Host "Supply a value for the To parameter"),
	[string]$From = $(Read-Host "Supply a value for the From parameter"),
	[string]$Subject = $(Read-Host "Supply a value for the Subject parameter"),
	[string]$Body = $(Read-Host "Supply a value for the Body parameter"),
	[string]$SmtpClient = $(Read-Host "Supply a value for the SmtpClient parameter")
)
$message = New-Object System.Net.Mail.MailMessage
foreach($Recipient in $To){ $message.To.Add($Recipient) }
$message.From = $From
$message.Subject = $Subject
$message.Body = $Body
$smtp = New-Object system.Net.Mail.SmtpClient $SmtpClient
$smtp.Send($message)

Category:Scripting, Windows PowerShell | Comment (0) | Author: Frank-Peter

How To Test For Application In $Env:PATH?

Sunday, 18. October 2009 11:02

Let’s assume your PowerShell script depends on a utility like robocopy.exe or sc.exe that is in a path listed in the Path environment variable ($Env:Path). Naturally, you want to test if that utility is present. While the Test-Path Cmdlet doesn’t take the Path environment variable into account the Get-Command Cmdlet is designed to consider that variable.

The function below, Test-EnvPath, uses Get-Command and returns True if the tested utility exists:

function Test-EnvPath
{
  param (
    [string]$Name = $(Read-Host "Supply a value for the Name parameter")
  )
  [array]$test = Get-Command -Name $Name -CommandType Application -ErrorAction SilentlyContinue
  if ($test.Count)
  {
    return $true
  }
  else
  {
    return $false
  }
}

The usage of Test-EnvPath is pretty simple:

if (-not (Test-EnvPath robocopy.exe))
{
  Write-Host "Required utility not found - robocopy.exe"
}

Category:Scripting, Windows PowerShell | Comment (0) | Author: Frank-Peter

How To Start A Process And Wait For It To Complete?

Sunday, 11. October 2009 15:50

One of the new Cmdlets introduced with PowerShell v2 is called Start-Process. It starts a process on the local computer and optionally waits for it to complete if you use the Cmdlet’s Wait switch parameter. Start-Process is implemented by using the Start method of the System.Diagnostics.Process class of the NET Framework.

The first release of Windows PowerShell didn’t came with a Cmdlet like Start-Process. The function below, it is called Start-Process as well, waits for process completion by default. Additionally, the function will wait for all child processes of the process to complete if you use the WaitForChildProcesses switch parameter. Furthermore, the function will not wait infinitely since it supports a Timeout parameter. By default, it will wait 600 seconds for a process (and child processes) to complete. Like Posh v2′s Start-Process the function uses the System.Diagnostics.Process NET Framework class.

So, why wait for child processes? If it is important to wait for process completion, maybe waiting for its child processes to complete matters as well. For example, the Oracle installer invokes Java and terminates while the Java Runtime is still busy installing the software.

Furthermore, I consider a Timeout as mandatory to avoid an infinite waiting due to a hanging process (or child process).

BTW, of course you can use the function in PowerShell v2 too. Remember that the function has two advantages: wait for child processes, and timeout!

# NAME
#     Start-Process.ps1
#
# SYNOPSIS
#     Starts a process and waits for it to complete.
#
# SYNTAX
#     Start-Process -FilePath <string> -ArgumentList <string> -Timeout <int> -WaitForChildProcesses
#
# DETAILED DESCRIPTION
#     http://www.fpschultze.de/news+article.storyid+121.htm
#
# $Date: 2009-10-11 16:14:40 +0200 (So, 11 Okt 2009) $
# $Rev: 1 $
# $Author: fpschultze $
# $URL: http://fpschultze.unfuddle.com/svn/fpschultze_ps-start-process/Start-Process.ps1 $

function Start-Process (
  [string]$FilePath = $(Read-Host "Supply a value for the FilePath parameter"),
  [string]$ArgumentList,
  [int]$Timeout = 600,
  [switch]$WaitForChildProcesses
){
  $Timeoutms = $Timeout * 1000
  $ProcessStartInfo = New-Object System.Diagnostics.ProcessStartInfo $FilePath
  if ($ArgumentList) { $ProcessStartInfo.Arguments = $ArgumentList }
  $Process = [System.Diagnostics.Process]::Start($ProcessStartInfo)
  $ProcessId = $Process.Id
  $ProcessStartTime = $Process.StartTime
  $ProcessCompleted = $Process.WaitForExit($Timeoutms)
  while ($WaitForChildProcesses -and $ProcessCompleted)
  {
    [array]$ChildProcesses = Get-WmiObject Win32_Process -Filter "ParentProcessId = $ProcessId"
    if (!$ChildProcesses.Count)
    {
      break
    }
    $Elapsedms = (New-TimeSpan $ProcessStartTime (Get-Date)).TotalMilliseconds
    if ($Elapsedms -lt $Timeoutms)
    {
      Start-Sleep -Seconds 1
    }
    else
    {
      $ProcessCompleted = $false
    }
  }
  return $ProcessCompleted
}

Category:Scripting, Windows PowerShell | Comment (0) | Author: Frank-Peter

Notepad++ Language File For PowerShell v2

Thursday, 8. October 2009 13:40

With this article I want to share my user defined language file for the popular Notepad++ editor. It is for both, PowerShell 1.0 and 2.0, and it uses the same colors like the PowerGUI Script Editor.

Installing a user defined language file for Notepad++ that someone else has written is pretty simple as long as you haven’t installed any previously: save the file as userDefineLang.xml in your %APPDATA%\Notepad++\ directory.

If you’ve added other user defined languages, you need to merge the two XML files. That’s pretty bad on the user experience side, but if you’re the kind of person who needs two user defined languages, you’re a total geek who loves merging XML files anyways ;-)

<NotepadPlus>
    <UserLang name="PowerShell" ext="ps1">
        <Settings>
            <Global caseIgnored="yes" />
            <TreatAsSymbol comment="yes" commentLine="yes" />
            <Prefix words1="no" words2="no" words3="no" words4="yes" />
        </Settings>
        <KeywordLists>
            <Keywords name="Delimiters">&quot;&apos;0&quot;&apos;0</Keywords>
            <Keywords name="Folder+">{ (</Keywords>
            <Keywords name="Folder-">} )</Keywords>
            <Keywords name="Operators">% * / + &lt; = &gt;</Keywords>
            <Keywords name="Comment"> 1&lt;# 2#&gt; 0#</Keywords>
            <Keywords name="Words1">Add-Computer Add-Content Add-History Add-Member Add-PSSnapin Add-Type Checkpoint-Computer Clear-Content Clear-EventLog Clear-History Clear-Item Clear-ItemProperty Clear-Variable Compare-Object Complete-Transaction Connect-WSMan ConvertFrom-Csv ConvertFrom-SecureString ConvertFrom-StringData Convert-Path ConvertTo-Csv ConvertTo-Html ConvertTo-SecureString ConvertTo-Xml Copy-Item Copy-ItemProperty Debug-Process Disable-ComputerRestore Disable-PSBreakpoint Disable-PSSessionConfiguration Disable-WSManCredSSP Disconnect-WSMan Enable-ComputerRestore Enable-PSBreakpoint Enable-PSRemoting Enable-PSSessionConfiguration Enable-WSManCredSSP Enter-PSSession Exit-PSSession Export-Alias Export-Clixml Export-Console Export-Counter Export-Csv Export-FormatData Export-ModuleMember Export-PSSession ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-ComputerRestorePoint Get-Content Get-Counter Get-Credential Get-Culture Get-Date Get-Event Get-EventLog Get-EventSubscriber Get-ExecutionPolicy Get-FormatData Get-Help Get-History Get-Host Get-HotFix Get-Item Get-ItemProperty Get-Job Get-Location Get-Member Get-Module Get-PfxCertificate Get-Process Get-PSBreakpoint Get-PSCallStack Get-PSDrive Get-PSProvider Get-PSSession Get-PSSessionConfiguration Get-PSSnapin Get-Random Get-Service Get-TraceSource Get-Transaction Get-UICulture Get-Unique Get-Variable Get-WinEvent Get-WmiObject Get-WSManCredSSP Get-WSManInstance Group-Object Import-Alias Import-Clixml Import-Counter Import-Csv Import-LocalizedData Import-Module Import-PSSession Invoke-Command Invoke-Expression Invoke-History Invoke-Item Invoke-WmiMethod Invoke-WSManAction Join-Path Limit-EventLog Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Event New-EventLog New-Item New-ItemProperty New-Module New-ModuleManifest New-Object New-PSDrive New-PSSession New-PSSessionOption New-Service New-TimeSpan New-Variable New-WebServiceProxy New-WSManInstance New-WSManSessionOption Out-Default Out-File Out-GridView Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Receive-Job Register-EngineEvent Register-ObjectEvent Register-PSSessionConfiguration Register-WmiEvent Remove-Computer Remove-Event Remove-EventLog Remove-Item Remove-ItemProperty Remove-Job Remove-Module Remove-PSBreakpoint Remove-PSDrive Remove-PSSession Remove-PSSnapin Remove-Variable Remove-WmiObject Remove-WSManInstance Rename-Item Rename-ItemProperty Reset-ComputerMachinePassword Resolve-Path Restart-Computer Restart-Service Restore-Computer Resume-Service Select-Object Select-String Select-Xml Send-MailMessage Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSBreakpoint Set-PSDebug Set-PSSessionConfiguration Set-Service Set-StrictMode Set-TraceSource Set-Variable Set-WmiInstance Set-WSManInstance Set-WSManQuickConfig Show-EventLog Sort-Object Split-Path Start-Job Start-Process Start-Service Start-Sleep Start-Transaction Start-Transcript Stop-Computer Stop-Job Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-ComputerSecureChannel Test-Connection Test-ModuleManifest Test-Path Test-WSMan Trace-Command Undo-Transaction Unregister-Event Unregister-PSSessionConfiguration Update-FormatData Update-List Update-TypeData Use-Transaction Wait-Event Wait-Job Wait-Process Where-Object Write-Debug Write-Error Write-EventLog Write-Host Write-Output Write-Progress Write-Verbose Write-Warning ac asnp clc cli clp clv cpi cpp cvpa diff epal epcsv fc fl % ft fw gal gc gci gcm gdr ghy gi gl gm gp gps group gsv gsnp gu gv gwmi iex ihy ii ipal ipcsv mi mp nal ndr ni nv oh rdr ri rni rnp rp rsnp rv rvpa sal sasv sc select si sl sleep sort sp spps spsv sv tee ? write cat cd clear cp h history kill lp ls mount mv popd ps pushd pwd r rm rmdir echo cls chdir copy del dir erase move rd ren set type</Keywords>
            <Keywords name="Words2">break continue do for foreach while if switch until where function filter else elseif in return exit param</Keywords>
            <Keywords name="Words3">-eq -ne -ge -gt -lt -le -like -notlike -match -notmatch -replace -contains -notcontains -ieq -ine -ige -igt -ile -ilt -ilike -inotlike -imatch -inotmatch -ireplace -icontains -inotcontains -ceq -cne -cge -cgt -clt -cle -clike -cnotlike -cmatch -cnotmatch -creplace -ccontains -cnotcontains -is -isnot -as = += -= *= /= %= -and -or -band -bor</Keywords>
            <Keywords name="Words4">$</Keywords>
        </KeywordLists>
        <Styles>
            <WordsStyle name="DEFAULT" styleID="11" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="FOLDEROPEN" styleID="12" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="1" />
            <WordsStyle name="FOLDERCLOSE" styleID="13" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="1" />
            <WordsStyle name="KEYWORD1" styleID="5" fgColor="008080" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="KEYWORD2" styleID="6" fgColor="0000FF" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="KEYWORD3" styleID="7" fgColor="FF0000" bgColor="FFFFFF" fontName="" fontStyle="1" />
            <WordsStyle name="KEYWORD4" styleID="8" fgColor="800080" bgColor="FFFFFF" fontName="" fontStyle="0" fontSize="10" />
            <WordsStyle name="COMMENT" styleID="1" fgColor="008000" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="COMMENT LINE" styleID="2" fgColor="008000" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="NUMBER" styleID="4" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="OPERATOR" styleID="10" fgColor="FF0000" bgColor="FFFFFF" fontName="" fontStyle="1" />
            <WordsStyle name="DELIMINER1" styleID="14" fgColor="800000" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="DELIMINER2" styleID="15" fgColor="800000" bgColor="FFFFFF" fontName="" fontStyle="0" />
            <WordsStyle name="DELIMINER3" styleID="16" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" />
        </Styles>
    </UserLang>
</NotepadPlus>

Category:Utilities, Windows PowerShell | Comments (1) | Author: Frank-Peter