Example of a PowerShell script converted to HTML with syntax highlighting
Posted by Roman Kuzmin in PowerShell on March 16, 2007
This is not a real script, it is a script used for testing of syntax description PowerShell.hrc for Colorer and covering related issues. Perhaps this HTML looks like a Christmas Tree, no problem, it is just a demo. One can configure Colorer according to his preferences. Take a look at how it handles and distinguishes expandable and not expandable string content and escaping rules, is not it a beauty?
Demo: highlighted PowerShell
EDIT: replaced large demo text with a link
Get-Drive.ps1 and Get-File.ps1 – Get all local files
Posted by Roman Kuzmin in PowerShell on December 14, 2006
Synopsis
The task of iterating through all local files may be not straightforward if there are several drives including removable, network or substituted drives and NTFS reparse points directories. Get-Drive.ps1 and Get-File.ps1 used together may help: Get-Drive.ps1 returns only local physical drives, Get-File.ps1 excludes reparse points.
Examples
# calculate total available free space in GB (Get-Drive | Measure-Object AvailableFreeSpace -Sum).Sum/1GB # get paths of all local .bak files Get-File \ *.bak -Name
Get-Drive.ps1
## ## Author : Roman Kuzmin ## Synopsis : Get physical drives ## ## Returns System.IO.DriveInfo objects ## ## *) removable, network and subst drives are excluded. ## $subst = [string](subst) foreach($d in [System.IO.DriveInfo]::GetDrives()) { if ($d.DriveType -eq 'Fixed' -and $subst -notlike "*$($d.Name):*") { $d } }
Get-File.ps1
## ## Author : Roman Kuzmin ## Synopsis : Get all files ## ## Returns System.IO.FileInfo objects or full names. ## -Root: root directory(s); single \ or // denotes all physical drives. ## -Filter: simple file system filter. ## -Name: return full names as strings. ## ## *) requires Get-Drive.ps1. ## *) access errors are silently ignored. ## *) hidden and system files are included. ## *) reparse points directories are excluded. ## param ( [string[]]$Root = '.', [string]$Filter = '*', [switch]$Name ) function DirectoryFiles([System.IO.DirectoryInfo]$di) { # ignore errors trap {continue} # skip a reparse point if ($di.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { return } # files if ($Name) { foreach($f in $di.GetFiles($Filter)) { $f.FullName } } else { $di.GetFiles($Filter) } # directories foreach($d in $di.GetDirectories()) { DirectoryFiles $d } } if ($Root.Count -eq 1 -and ($Root[0] -eq '\' -or $Root[0] -eq '//')) { foreach($d in Get-Drive) { DirectoryFiles $d.RootDirectory } } else { foreach($d in $Root) { DirectoryFiles $d } }
PowerShell syntax description for Colorer and Far Manager editor
Posted by Roman Kuzmin in PowerShell on December 7, 2006
Synopsis
PowerShell.hrc defines PowerShell syntax description for Colorer and Far Manager editor with FarColorer plugin.
EDIT: This version is obsolete. The latest PowerShell.hrc is included into the featured version of PowerShellFar plug-in for Far Manager:
http://code.google.com/p/farnet/
PowerShell.hrc
<?xml version="1.0" encoding="windows-1251"?>
<!DOCTYPE hrc PUBLIC "-//Cail Lomecb//DTD Colorer HRC take5//EN" "http://colorer.sf.net/2003/hrc.dtd">
<hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd">
<!--
Insert into catalog.xml a link to this:
<location link="<path>/PowerShell.hrc"/>
-->
<prototype name="PowerShell" group="scripts" description="PowerShell">
<filename>/(.ps1$|.ps1.bak$|.psfconsole$)/i</filename>
</prototype>
<type name="PowerShell">
<annotation>
<documentation>
PowerShell.hrc version 1.3.1, 2007.03.21
PowerShell syntax description and .psfconsole features.
Created and tested for PowerShell 1.0 with Colorer-take5.beta5
</documentation>
<contributors>
Roman Kuzmin, nightroman@hotmail.com
</contributors>
</annotation>
<import type="def"/>
<!-- Escaped -->
<scheme name="PSEscaped">
<regexp match="/`s+$/" region="def:Error"/>
<regexp match="/`./" region="def:StringContent"/>
</scheme>
<!-- Variable -->
<scheme name="PSVariable">
<regexp match="/$[w:]*w/" region="def:Var"/>
<block start="/${/" end="/}/" scheme="PSEscaped" region="def:Var" region00="def:PairStart" region10="def:PairEnd" region01="def:Var" region11="def:Var"/>
</scheme>
<!-- Expanded -->
<scheme name="PSExpanded">
<block start="/($()/" end="/())/" scheme="PowerShell" region00="def:PairStart" region10="def:PairEnd" region01="def:Var" region11="def:Var"/>
</scheme>
<!-- Array -->
<scheme name="PSArray">
<block start="/@(/" end="/)/" scheme="PowerShell" region00="def:PairStart" region10="def:PairEnd"/>
</scheme>
<!-- Hash -->
<scheme name="PSHash">
<block start="/@{/" end="/}/" scheme="PowerShell" region00="def:PairStart" region10="def:PairEnd"/>
</scheme>
<!-- Number -->
<entity name="psnumexp" value="(?:[eE][-+]?d+)"/>
<entity name="psnumsuf" value="([Ll]?(?:KB|MB|GB)?)"/>
<scheme name="PSNumber">
<regexp match="/B.?~1.d+%psnumexp;?%psnumsuf;b/i" region0="def:NumberFloat" region1="def:NumberSuffix"/>
<regexp match="/bd+..?!d*(?:%psnumexp;?%psnumsuf;b|B)/i" region0="def:NumberFloat" region1="def:NumberSuffix"/>
<regexp match="/bd+%psnumexp;%psnumsuf;b/i" region0="def:NumberFloat" region1="def:NumberSuffix"/>
<regexp match="/b0[xX][da-fA-F]+%psnumsuf;b/i" region0="def:NumberHex" region1="def:NumberSuffix"/>
<regexp match="/bd+%psnumsuf;b/i" region0="def:NumberDec" region1="def:NumberSuffix"/>
</scheme>
<!-- Content in '' -->
<scheme name="PSAposContent">
<regexp match="/''/" region="def:StringContent"/>
</scheme>
<!-- Content in "" -->
<scheme name="PSQuotContent">
<inherit scheme="PSEscaped"/>
<inherit scheme="PSVariable"/>
<inherit scheme="PSExpanded"/>
</scheme>
<!-- Content of output -->
<scheme name="PSOutputContent">
<regexp match="/^ERROR(?::|b)|<<<<(?:s|$)/" region="def:Error"/>
<regexp match="/^WARNINGb.*$/" region="def:StringContent"/>
<regexp match="/^(?
EBUG|VERBOSE)b.*$/" region="def:Comment"/>
<inherit scheme="PSNumber"/>
</scheme>
<!-- Main -->
<scheme name="PowerShell">
<!-- Output -->
<block start="/^x1A$/" end="/^x1B$/" scheme="PSOutputContent" region00="def:PairStart" region10="def:PairEnd"/>
<!-- Comments -->
<regexp match="/(?:^|s)###s+(.*)/" region="def:Comment" region1="def:Outlined"/>
<regexp match="/(?:^|s)##.*/" region="def:CommentDoc"/>
<regexp match="/(?:^|s)#.*/" region="def:Comment"/>
<!-- Apos-strings -->
<block start="/@x27$/" end="/^x27@/" scheme="PSAposContent" region="def:String" region00="def:PairStart" region10="def:PairEnd"/>
<block start="/x27/" end="/x27/" scheme="PSAposContent" region="def:String" region00="def:PairStart" region10="def:PairEnd"/>
<!-- Escaped -->
<inherit scheme="PSEscaped"/>
<!-- Expanded -->
<inherit scheme="PSExpanded"/>
<!-- Array -->
<inherit scheme="PSArray"/>
<!-- Hash -->
<inherit scheme="PSHash"/>
<!-- Quot-strings -->
<block start="/@x22$/" end="/^x22@/" scheme="PSQuotContent" region="def:String" region00="def:PairStart" region10="def:PairEnd"/>
<block start="/x22/" end="/x22/" scheme="PSQuotContent" region="def:String" region00="def:PairStart" region10="def:PairEnd"/>
<!-- Types [xxx.xxx], [xxx[]] except [1], [$i] -->
<regexp match="/[[A-Za-z][w.]*(?:[])*]/" region="def:TypeKeyword"/>
<!-- Brackets -->
<inherit scheme="def:PairedBrackets">
<virtual scheme="def:PairedBrackets" subst-scheme="PowerShell"/>
</inherit>
<!-- Function -->
<regexp match="/(?:^|~|[;}]?#1)s*(function|filter)s+([^s(]+)/i" region1="def:FunctionKeyword" region2="def:Identifier" region="def:Outlined"/>
<!-- Pipeline and redirection -->
<keywords ignorecase="yes" region="def:KeywordStrong">
<symb name="|"/>
<symb name=">"/>
<symb name=">>"/>
<symb name="2>"/>
<symb name="2>&1"/>
<symb name="2>>"/>
</keywords>
<!-- Redirection operators (not yet) -->
<keywords ignorecase="yes" region="def:Error">
<word name="<"/>
<word name="1>&2"/>
</keywords>
<!-- Numbers -->
<inherit scheme="PSNumber"/>
<!-- Cmdlets -->
<keywords ignorecase="yes" region="def:Keyword" worddiv="[s(){};=|]">
<word name="Add-Content"/>
<word name="Add-History"/>
<word name="Add-Member"/>
<word name="Add-PSSnapin"/>
<word name="Clear-Content"/>
<word name="Clear-Host"/>
<word name="Clear-Item"/>
<word name="Clear-ItemProperty"/>
<word name="Clear-Variable"/>
<word name="Compare-Object"/>
<word name="ConvertFrom-SecureString"/>
<word name="Convert-Path"/>
<word name="ConvertTo-Html"/>
<word name="ConvertTo-SecureString"/>
<word name="Copy-Item"/>
<word name="Copy-ItemProperty"/>
<word name="Export-Alias"/>
<word name="Export-Clixml"/>
<word name="Export-Console"/>
<word name="Export-Csv"/>
<word name="ForEach-Object"/>
<word name="Format-Custom"/>
<word name="Format-List"/>
<word name="Format-Table"/>
<word name="Format-Wide"/>
<word name="Get-Acl"/>
<word name="Get-Alias"/>
<word name="Get-AuthenticodeSignature"/>
<word name="Get-ChildItem"/>
<word name="Get-Command"/>
<word name="Get-Content"/>
<word name="Get-Credential"/>
<word name="Get-Culture"/>
<word name="Get-Date"/>
<word name="Get-EventLog"/>
<word name="Get-ExecutionPolicy"/>
<word name="Get-Help"/>
<word name="Get-History"/>
<word name="Get-Host"/>
<word name="Get-Item"/>
<word name="Get-ItemProperty"/>
<word name="Get-Location"/>
<word name="Get-Member"/>
<word name="Get-PfxCertificate"/>
<word name="Get-Process"/>
<word name="Get-PSDrive"/>
<word name="Get-PSProvider"/>
<word name="Get-PSSnapin"/>
<word name="Get-Service"/>
<word name="Get-TraceSource"/>
<word name="Get-UICulture"/>
<word name="Get-Unique"/>
<word name="Get-Variable"/>
<word name="Get-WmiObject"/>
<word name="Group-Object"/>
<word name="Import-Alias"/>
<word name="Import-Clixml"/>
<word name="Import-Csv"/>
<word name="Invoke-Expression"/>
<word name="Invoke-History"/>
<word name="Invoke-Item"/>
<word name="Join-Path"/>
<word name="Measure-Command"/>
<word name="Measure-Object"/>
<word name="Move-Item"/>
<word name="Move-ItemProperty"/>
<word name="New-Alias"/>
<word name="New-Item"/>
<word name="New-ItemProperty"/>
<word name="New-Object"/>
<word name="New-PSDrive"/>
<word name="New-Service"/>
<word name="New-TimeSpan"/>
<word name="New-Variable"/>
<word name="Out-Default"/>
<word name="Out-File"/>
<word name="Out-Host"/>
<word name="Out-Null"/>
<word name="Out-Printer"/>
<word name="Out-String"/>
<word name="Pop-Location"/>
<word name="Push-Location"/>
<word name="Read-Host"/>
<word name="Remove-Item"/>
<word name="Remove-ItemProperty"/>
<word name="Remove-PSDrive"/>
<word name="Remove-PSSnapin"/>
<word name="Remove-Variable"/>
<word name="Rename-Item"/>
<word name="Rename-ItemProperty"/>
<word name="Resolve-Path"/>
<word name="Restart-Service"/>
<word name="Resume-Service"/>
<word name="Select-Object"/>
<word name="Select-String"/>
<word name="Set-Acl"/>
<word name="Set-Alias"/>
<word name="Set-AuthenticodeSignature"/>
<word name="Set-Content"/>
<word name="Set-Date"/>
<word name="Set-ExecutionPolicy"/>
<word name="Set-Item"/>
<word name="Set-ItemProperty"/>
<word name="Set-Location"/>
<word name="Set-PSDebug"/>
<word name="Set-Service"/>
<word name="Set-TraceSource"/>
<word name="Set-Variable"/>
<word name="Sort-Object"/>
<word name="Split-Path"/>
<word name="Start-Service"/>
<word name="Start-Sleep"/>
<word name="Start-Transcript"/>
<word name="Stop-Process"/>
<word name="Stop-Service"/>
<word name="Stop-Transcript"/>
<word name="Suspend-Service"/>
<word name="Tee-Object"/>
<word name="Test-Path"/>
<word name="Trace-Command"/>
<word name="Update-FormatData"/>
<word name="Update-TypeData"/>
<word name="Where-Object"/>
<word name="Write-Debug"/>
<word name="Write-Error"/>
<word name="Write-Host"/>
<word name="Write-Output"/>
<word name="Write-Progress"/>
<word name="Write-Verbose"/>
<word name="Write-Warning"/>
</keywords>
<!-- System variables -->
<keywords ignorecase="yes" region="def:Constant">
<word name="$$"/>
<word name="$?"/>
<word name="$^"/>
<word name="$_"/>
<word name="$args"/>
<word name="$ConfirmPreference"/>
<word name="$ConsoleFileName"/>
<word name="$DebugPreference"/>
<word name="$Error"/>
<word name="$ErrorActionPreference"/>
<word name="$ErrorView"/>
<word name="$ExecutionContext"/>
<word name="$false"/>
<word name="$FormatEnumerationLimit"/>
<word name="$HOME"/>
<word name="$Host"/>
<word name="$input"/>
<word name="$LastExitCode"/>
<word name="$Matches"/>
<word name="$MaximumAliasCount"/>
<word name="$MaximumDriveCount"/>
<word name="$MaximumErrorCount"/>
<word name="$MaximumFunctionCount"/>
<word name="$MaximumHistoryCount"/>
<word name="$MaximumVariableCount"/>
<word name="$MyInvocation"/>
<word name="$NestedPromptLevel"/>
<word name="$null"/>
<word name="$OFS"/>
<word name="$PID"/>
<word name="$PROFILE"/>
<word name="$ProgressPreference"/>
<word name="$PSHOME"/>
<word name="$PWD"/>
<word name="$ReportErrorShowExceptionClass"/>
<word name="$ReportErrorShowInnerException"/>
<word name="$ReportErrorShowSource"/>
<word name="$ReportErrorShowStackTrace"/>
<word name="$ShellId"/>
<word name="$this"/>
<word name="$true"/>
<word name="$VerbosePreference"/>
<word name="$WarningPreference"/>
<word name="$WhatIfPreference"/>
</keywords>
<!-- User variables -->
<inherit scheme="PSVariable"/>
<!-- Operators -->
<keywords ignorecase="yes" region="def:Operator">
<word name="-eq"/>
<word name="-ne"/>
<word name="-ge"/>
<word name="-gt"/>
<word name="-lt"/>
<word name="-le"/>
<word name="-like"/>
<word name="-notlike"/>
<word name="-match"/>
<word name="-notmatch"/>
<word name="-replace"/>
<word name="-contains"/>
<word name="-notcontains"/>
<word name="-ieq"/>
<word name="-ine"/>
<word name="-ige"/>
<word name="-igt"/>
<word name="-ile"/>
<word name="-ilt"/>
<word name="-ilike"/>
<word name="-inotlike"/>
<word name="-imatch"/>
<word name="-inotmatch"/>
<word name="-ireplace"/>
<word name="-icontains"/>
<word name="-inotcontains"/>
<word name="-ceq"/>
<word name="-cne"/>
<word name="-cge"/>
<word name="-cgt"/>
<word name="-clt"/>
<word name="-cle"/>
<word name="-clike"/>
<word name="-cnotlike"/>
<word name="-cmatch"/>
<word name="-cnotmatch"/>
<word name="-creplace"/>
<word name="-ccontains"/>
<word name="-cnotcontains"/>
<word name="-is"/>
<word name="-isnot"/>
<word name="-as"/>
<word name="-and"/>
<word name="-not"/>
<word name="-or"/>
<word name="-xor"/>
<word name="-band"/>
<word name="-bor"/>
<word name="-bxor"/>
<word name="-f"/>
<symb name="--"/>
<symb name="++"/>
<symb name="+="/>
<symb name="-="/>
<symb name="*="/>
<symb name="/="/>
<symb name="%="/>
<symb name="="/>
<symb name="+"/>
<symb name="*"/>
<symb name="/"/>
<symb name="%"/>
</keywords>
<!-- Operator - -->
<regexp match="/-[A-Za-z_]?!/" region="def:Operator"/>
<!-- Keywords (filter and function are excluded) -->
<keywords ignorecase="yes" region="def:Keyword" worddiv="[s(){};]">
<word name="begin"/>
<word name="break"/>
<word name="continue"/>
<word name="default"/>
<word name="do"/>
<word name="else"/>
<word name="elseif"/>
<word name="end"/>
<word name="exit"/>
<word name="finally"/>
<word name="for"/>
<word name="foreach"/>
<word name="if"/>
<word name="in"/>
<word name="param"/>
<word name="process"/>
<word name="return"/>
<word name="switch"/>
<word name="throw"/>
<word name="trap"/>
<word name="until"/>
<word name="while"/>
</keywords>
<!-- Identifiers (very simplified) -->
<regexp match="/[A-Za-z_][-w]*/" region="def:Identifier"/>
<!-- Error: (ok, warning): redundant semicolon -->
<regexp match="/;s*}?(?:s*|s+#.*)$/" region="def:Error"/>
<!-- Error: bad string: symbols after @' or @" -->
<regexp match="/@[x22x27].$/" region="def:Error"/>
<!-- Separators -->
<regexp match="/[,;]/" region="def:Operator"/>
</scheme>
</type>
</hrc>
<!-- ***** BEGIN LICENSE BLOCK *****
- Version: MPL 1.1/GPL 2.0/LGPL 2.1
-
- The contents of this file are subject to the Mozilla Public License Version
- 1.1 (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
http://www.mozilla.org/MPL/
-
- Software distributed under the License is distributed on an "AS IS" basis,
- WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- for the specific language governing rights and limitations under the
- License.
-
- The Original Code is the Colorer Library.
-
- The Initial Developer of the Original Code is
- Cail Lomecb <cail@nm.ru>.
- Portions created by the Initial Developer are Copyright (C) 1999-2005
- the Initial Developer. All Rights Reserved.
-
- Contributor(s):
- Roman Kuzmin <nightroman@hotmail.com>
-
- Alternatively, the contents of this file may be used under the terms of
- either the GNU General Public License Version 2 or later (the "GPL"), or
- the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- in which case the provisions of the GPL or the LGPL are applicable instead
- of those above. If you wish to allow use of your version of this file only
- under the terms of either the GPL or the LGPL, and not to allow others to
- use your version of this file under the terms of the MPL, indicate your
- decision by deleting the provisions above and replace them with the notice
- and other provisions required by the LGPL or the GPL. If you do not delete
- the provisions above, a recipient may use your version of this file under
- the terms of any one of the MPL, the GPL or the LGPL.
-
- ***** END LICENSE BLOCK ***** -->
Resize-Console.ps1 – Resize console window/buffer using arrow keys
Posted by Roman Kuzmin in PowerShell on November 17, 2006
Synopsis
Perhaps resizing of Windows console is quite tricky. This script makes it easy with arrow keys.
Resize-Console.ps1
##
## Author : Roman Kuzmin
## Synopsis : Resize console window/buffer using arrow keys
##
function Size($w, $h)
{
New-Object System.Management.Automation.Host.Size($w, $h)
}
Write-Host '[Arrows] resize [Esc] exit ...'
$ErrorActionPreference = 'SilentlyContinue'
for($ui = $Host.UI.RawUI;;) {
$b = $ui.BufferSize
$w = $ui.WindowSize
switch($ui.ReadKey(6).VirtualKeyCode) {
37 {
$w = Size ($w.width - 1) $w.height
$ui.WindowSize = $w
$ui.BufferSize = Size $w.width $b.height
break
}
39 {
$w = Size ($w.width + 1) $w.height
$ui.BufferSize = Size $w.width $b.height
$ui.WindowSize = $w
break
}
38 {
$ui.WindowSize = Size $w.width ($w.height - 1)
break
}
40 {
$w = Size $w.width ($w.height + 1)
if ($w.height -gt $b.height) {
$ui.BufferSize = Size $b.width $w.height
}
$ui.WindowSize = $w
break
}
27 {
return
}
}
}
Format-Chart.ps1 – Formats output as a table with a chart column
Posted by Roman Kuzmin in PowerShell on November 4, 2006
Synopsis
The script formats output as a table with a pseudo-graphical chart column calculated for the last specified numeric property.
Examples
# Chart of process working sets ps | Format-Chart Id, Name, WS # Chart of file sizes in descending order dir | sort Length -desc | Format-Chart Name, Length
Format-Chart.ps1
##
## Author : Roman Kuzmin
## Synopsis : Formats output as a table with a chart column
## Modified : 2006.11.06
##
## -Property: properties where the last one is numeric for a chart.
## -Width: chart column width, default is 1/2 of screen buffer.
## -ForeChar: character for chart bars.
## -BackChar: character for appending bars.
## -InputObject: the objects to be formatted.
##
param
(
[object[]]$Property = $(throw 'Supply properties'),
[int]$Width = ($Host.UI.RawUI.BufferSize.Width/2),
[char]$ForeChar = 9600,
[char]$BackChar = 9617,
[object[]]$InputObject
)
$set = $(if ($InputObject) {$InputObject} else {@($Input)}) |
Select-Object $Property
$max = ($set | Measure-Object ($Property[-1]) -Maximum).Maximum
if ($max -eq 0) {$max = 1}
$set | .{process{
$_ | Add-Member -PassThru NoteProperty Chart (("$ForeChar"*(
$_.$($Property[-1])/$max*$Width)).PadRight($Width, $BackChar))
}} |
Format-Table ($Property + 'Chart') -AutoSize
Get-Calendar.ps1 – Shows a month calendar control and returns selected dates
Posted by Roman Kuzmin in PowerShell on October 15, 2006
The idea is borrowed from the //o//’s blog //o// PowerShelled: Calendar Function (GUI). It is nice and simple. Perhaps a few touches here make it more customizable and useful for wider range of tasks.
Synopsis
The script works as date(s) viewer/picker. It shows WinForm dialog with a month calendar control with predefined date(s) selected and returns start and end date of initial or changed date range. By default 12 months (3 columns, 4 rows) are shown. Week numbers may be optionally turned on by a switch.
Examples
# Select dates and get number of days including the end date $dates = Get-Calendar ($dates[1] - $dates[0]).TotalDays + 1 # Use predefined range, two months view and week numbers shown $start, $end = Get-Calendar '2006.10.16' '2006.11.16' 2,1 -week Write-Host "Start: $start. End: $end."
Get-Calendar.ps1
##
## Author : Roman Kuzmin inspired by //o// www.ThePowerShellGuy.com
## Synopsis : Shows a month calendar control and returns selected dates
## Modified : 2006.10.15
##
## Returns an array of two selected start and end dates
## -Start <datetime>: initial start date
## -End <datetime>: initial end date
## -Dimensions <int[]>: (columns, rows) of months
## -WeekNumbers <switch>: show week numbers
##
## *) Press Enter to return currently selected dates.
## *) Press Escape or close the form to return initial dates.
##
param
(
[datetime]$Start = [datetime]::Now,
[datetime]$End = $Start,
[int[]]$Dimensions = (3, 4),
[switch]$WeekNumbers
)
# load forms
& {[void][System.Windows.Forms.Form]; trap {[void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); continue}}
# new calendar
$cal = New-Object System.Windows.Forms.MonthCalendar
$cal.CalendarDimensions = New-Object System.Drawing.Size $Dimensions
$cal.Margin = New-Object System.Windows.Forms.Padding 0
$cal.MaxSelectionCount = 366
$cal.SelectionRange = New-Object System.Windows.Forms.SelectionRange $Start, $End
$cal.ShowWeekNumbers = $WeekNumbers
# new form
$form = New-Object System.Windows.Forms.Form
$form.AutoSize = $true
$form.AutoSizeMode = 'GrowAndShrink'
$form.FormBorderStyle = 'FixedDialog'
$form.KeyPreview = $true
$form.MaximizeBox = $false
$form.Text = 'Calendar'
$form.Controls.Add($cal)
$form.add_Shown({$form.Activate()})
$form.add_KeyDown({
switch($_.KeyCode) {
'Escape' {$form.Close()}
'Return' {$form.Close(); $Start = $cal.SelectionRange.Start; $End = $cal.SelectionRange.End}
}
})
# show and return dates
[void]$form.ShowDialog()
$Start.Date, $End.Date
Get-Choice.ps1 – Displays PowerShell style menu and gets a user choice
Posted by Roman Kuzmin in PowerShell on October 13, 2006
##
## Author : Roman Kuzmin
## Synopsis : Displays PowerShell style menu and gets a user choice
## Modified : 2006.10.13
##
## Returns a choice index
## -caption <string>: menu caption
## -message <string>: menu message
## -choices <string[]>: pairs: item1, help1, item2, help2, ...
## -defaultChoice <int>: default choice index
##
## *) Choice keys are indicated by '&' in menu items.
##
param
(
[string]$caption = 'Confirm',
[string]$message = 'Are you sure you want to continue?',
[string[]]$choices = ('&Yes', 'Continue', '&No', 'Stop'),
[int]$defaultChoice = 0
)
$choiceDescriptions = @()
for($i = 0; $i -lt $choices.Count; $i += 2)
{
$c = [System.Management.Automation.Host.ChoiceDescription]$choices[$i]
$c.HelpMessage = $choices[$i + 1]
$choiceDescriptions += $c
}
$Host.UI.PromptForChoice($caption, $message, [System.Management.Automation.Host.ChoiceDescription[]]$choiceDescriptions, $defaultChoice)
EDIT: See also the modified version for multiple choices here.
Recent Comments