In response to the comment about using IsePack
A recommendation for using PowerShellPack’s IsePack Copy-ColoredAsHtml has been made in the comment to my post. I’m not a big fan of this huge package, but this is worth testing for publishing.
I use the same code copy-pasted from an ISE tab:
cls
#region WordPress posting code test
#this is a test of Powershell code coloring
[string]$stringVar1 = "string 1";
[string]$private:stringVar2 = 'string 2';
[string]$script:stringVar3=
@'
string data
'@
[scriptblock]$global:sb = {{Write-Host scriptblock}.Invoke();};
function
write1{Write-Host $stringVar1;}
function private:write2
{param([string]$str2 = '')
Write-Host $str2;}
function script:write3
#this is a function
{
Write-Host $script:stringVar3;
}
function global:Print-SB
{
<#
.SYNOPSIS
This is a code coloring test.
.DESCRIPTION
This test function represents an advanced Powershell function syntax.
.PARAMETER Param
Demonstrates how a scriptblock can be passed as a reference.
.EXAMPLE
PS C:\> Print-SB ([ref]$sb)
#>
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)]
[ref]$Param
)
Begin{}
Process{$Param.Value.Invoke()}
End{}
}
write1
private:write2 $private:stringVar2;
script:write3
Print-SB ([ref]$global:sb)
#endregion WordPress posting code test
Below is the result of IsePack code preparation:
cls #region WordPress posting code test #this is a test of Powershell code coloring [string]$stringVar1 = "string 1"; [string]$private:stringVar2 = 'string 2'; [string]$script:stringVar3= @' string data '@ [scriptblock]$global:sb = {{Write-Host scriptblock}.Invoke();}; function write1{Write-Host $stringVar1;} function private:write2 {param([string]$str2 = '') Write-Host $str2;} function script:write3 #this is a function { Write-Host $script:stringVar3; } function global:Print-SB { Print-SB ([ref]$sb) #> [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [ref]$Param ) Begin{} Process{$Param.Value.Invoke()} End{} } write1 private:write2 $private:stringVar2; script:write3 Print-SB ([ref]$global:sb) #endregion WordPress posting code test
This looks great and very similar to the hand-made colored code from my post. But who has stolen my advanced function’s comment?! 🙂 All the text between <# and C:\> inclusively erased as a cow licked out.
A hand-made script-to-form converter (sooner a sample than a tool)
With eternal love to automation, I began today a small project aiming to help creation of PowerShell GUI forms. This post is the first step, will or won’t I do the next is not clearly even to me.
A year ago I wrote something like this. It was a PropertiesBrowser module/add-on, which I used as the Watches window, typical of any IDE, sometimes. It hasn’t been published, though.
Having today morning an hour or slightly more, I decided to write a post mostly to test the new smartbook I own the third day, but at the same time I caught what I want. A simple form generator.
How should it work? Almost every script produces an output. Strings, numbers, boolean, objects, all what may return a PowerShell code. Why don’t allow the scripter to put it on a form without an effort? Sound like a GUI modeling tool (but looks much more uglyer).
Here it is, the code giving some output and used as a sample:
cls
Set-StrictMode -Version Latest
Import-Module FormGen -Force
[int]$i = 3;
Set-OutputToForm $i
Set-OutputToForm $i -SuppressLabel $true
Set-OutputToForm $i -Description "int"
$f = New-Object System.Windows.Forms.Form
Set-OutputToForm $f;
$a = @("s", "T");
Set-OutputToForm $a $false "Array"
Get-ChildItem | Select-Object -First 3 | %{Set-OutputToForm $_ -Description "fileinfo of $($_.FullName)";}
1..2 | %{Set-OutputToForm $_;}
Get-ChildItem | Select-Object -First 1 | %{Set-OutputToForm $_ -Description "fileinfo of $($_.FullName)" -ControlType 'System.Windows.Forms.ListView';}
Get-ChildItem | Select-Object -First 1 | %{Set-OutputToForm $_ -Description "fileinfo of $($_.FullName)" -ControlType 'System.Windows.Forms.TreeView';}
Get-ChildItem | Select-Object -First 1 | %{Set-OutputToForm $_ -Description "fileinfo of $($_.FullName)" -ControlType 'System.Windows.Forms.ComboBox';}
Show-Result;
As can be seen, there is the FormGen module and two functions exported from it, Set-OutputToForm and Show-Result. While the former adds data to a form still invisible, the latter, to be used once, displays the form.
Set-StrictMode -Version Latest
[int]$script:topPosition = 0;
[System.Windows.Forms.Form]$script:frmMain = `
New-Object System.Windows.Forms.Form;
$script:frmMain.Width = 500;
function Set-OutputToForm
{
Set-OutputToForm $data
PS> 1..10 | %{Set-OutputToForm $_;}
PS> Get-ChildItem | %{Set-OutputToForm $_ -SuppressLabel $true; $null;}
.Notes
Author: Alexander Petrovskiy
#>
[CmdletBinding()]
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
$InputObject,
[bool]$SuppressLabel = $false,
[string]$Description = "",
[string]$ControlType = ""
)
Begin{}
Process{
[bool]$result = $false;
try{
if (-not $SuppressLabel)
{
[System.Windows.Forms.Label]$private:label = `
New-Object System.Windows.Forms.Label;
$script:topPosition += 10;
$private:label.Top = $script:topPosition;
$private:label.Left = 50;
$private:label.Width = $script:frmMain.Width - 50;
$private:label.Visible = $true;
if ($Description.Length -gt 0)
{
$private:label.Text = $Description;
}
else
{
$private:label.Text = $InputObject.GetType().ToString();
}
$script:frmMain.Controls.Add($private:label);
$script:topPosition += $private:label.Height;
}
[bool]$private:useCustomControl = $false;
[System.Windows.Forms.Control]$private:ctrl = `
New-Object System.Windows.Forms.Control;
if ($ControlType.Length -gt 0)
{
try{[System.Windows.Forms.Control]$private:ctrl =
New-Object $ControlType;
$private:useCustomControl = $true;
}catch{$private:useCustomControl = $false;}
}
#of which type these data?
#an array?
if ($InputObject -is [System.Array])
{
if (-not $private:useCustomControl){
[System.Windows.Forms.ListBox]$private:ctrl = `
New-Object System.Windows.Forms.ListBox;}
for($private:i = 0; $private:i -lt $InputObject.Length;
$private:i++)
{
if ($private:ctrl -is [System.Windows.Forms.ListBox] -or `
$private:ctrl -is [System.Windows.Forms.ComboBox] -or `
$private:ctrl -is [System.Windows.Forms.ListView]){
$private:ctrl.Items.Add($InputObject[$private:i]);}
if ($private:ctrl -is [System.Windows.Forms.TreeView]){
$private:ctrl.Nodes.Add($InputObject[$private:i]);}
}
}
#a string? int one? other simple type?
elseif ($InputObject.GetType().BaseType.Name -eq 'ValueType')
{
if (-not $private:useCustomControl){
[System.Windows.Forms.Label]$private:ctrl = `
New-Object System.Windows.Forms.Label;}
if ($private:ctrl -is [System.Windows.Forms.ListBox] -or `
$private:ctrl -is [System.Windows.Forms.ComboBox] -or `
$private:ctrl -is [System.Windows.Forms.ListView]){
$private:ctrl.Items.Add($InputObject.ToString());}
if ($private:ctrl -is [System.Windows.Forms.TreeView]){
$private:ctrl.Nodes.Add($InputObject.ToString());}
if ($private:ctrl -is [System.Windows.Forms.Label] -or `
$private:ctrl -is [System.Windows.Forms.TextBox]){
$private:ctrl.Text = $InputObject.ToString();}
}
else
{
if (-not $private:useCustomControl){
[System.Windows.Forms.PropertyGrid]$private:ctrl = `
New-Object System.Windows.Forms.PropertyGrid;}
if ($private:ctrl -is [System.Windows.Forms.PropertyGrid]){
$private:ctrl.SelectedObject = $InputObject;}
if ($private:ctrl -is [System.Windows.Forms.ListBox] -or `
$private:ctrl -is [System.Windows.Forms.ComboBox] -or `
$private:ctrl -is [System.Windows.Forms.ListView]){
$private:ctrl.Items.Add($InputObject.ToString());}
if ($private:ctrl -is [System.Windows.Forms.TreeView]){
$private:ctrl.Nodes.Add($InputObject.ToString());}
}
#common properties
$private:ctrl.Left = 50;
$private:ctrl.Top = $script:topPosition;
$private:ctrl.Visible = $true;
$script:frmMain.Controls.Add($private:ctrl);
$script:topPosition += $private:ctrl.Height;
}catch{}
$result = $true;
return $result;}
End{}
}
function Show-Result
{
$script:frmMain.Height = $script:topPosition + 40;
$script:frmMain.ShowDialog() | Out-Null;
}
Export-ModuleMember -Function Set-OutputToForm, Show-Result;
Need to repeat, this is sooner a concept than a ready-to-use tool, so that use it as is. Probably, I’ll update it. The current version attached here.
Although it’s not an advantage for powershellers, I’m proud that at least a half of this code was written on my Android smartbook. This means that I can write from more places than I could before. I have had for two years a netbook, but without 3G and its keyboard was damaged on travel. Gladly, now I can write on the go again, with the actually mobile device.
WordPress and PowerShell Code. The Second Try
Last week I complained about how it is not easy to post Powershell code here. The letter of my dissatisfaction has been sent to and the answer was received from the WordPress support.
As a first step of our efforts to improve the code coloration was the question about what is wrong and what I’ve wanted. Of course, I assured the support specialist that I’ll provide so many examples of code that they will be able to polish publishing if they want to. That time the code sample appeared as on the following figure:
This post is the next step. I copy-pasted the WordPress code from my previous post on this topic to LibreOffice Writer 3.3, marked the most of significant blocks of code with several colors and put it back to WordPress page as an HTML.
Below is what I’d expect I might have had in my blog when I use the ‘sourcecode’ tag:
cls
#region WordPress posting code test
#this is a test of Powershell code coloring
[string]$stringVar1 = “string 1”;
[string]$private:stringVar2 = ‘string 2’;
[string]$script:stringVar3=
@’
string data
‘@
[scriptblock]$global:sb = {{Write-Host scriptblock}.Invoke();};
function
write1{Write-Host $stringVar1;}
function private:write2
{param([string]$str2 = ”)Write-Host $str2;}
function script:write3
#this is a function
{
Write-Host $script:stringVar3;
}
function global:Print-SB
{
<#
.SYNOPSIS
This is a code coloring test.
.DESCRIPTION
This test function represents an advanced Powershell function syntax.
.PARAMETER Param
Demonstrates how a scriptblock can be passed as a reference.
.EXAMPLE
PS C:\> Print-SB ([ref]$sb)
#>
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)]
[ref]$Param
)
Begin{}
Process{$Param.Value.Invoke()}
End{}
}
write1
private:write2 $private:stringVar2;
script:write3
Print-SB ([ref]$global:sb)
#endregion WordPress posting code test
I divided all the sample code into several meaningful groups. Although the exact color schema is a subject of possible further discussion, I used some, taken from both Powershell ISE and PowerGUI as an average. Here are groups instructions of the sample were split into.
1) the comments (green) group includes one-string comment beginning with the # sign and a multi-string comment applicable for advanced functions and consisting of all between <# and #> character sequences (sequences are included too).
2) commandlets and commands (some blue-gray color that has been used in the original WordPress’s coloration), and their aliases like Out-Null, Get-ChildItem, dir. There is a fixed list of them. Custom aliases and commandlets are not supposed to be colored due to the fact that WordPress doesn’t run any PS code and it’s completely unaware of new constructs.
3) data types and attributes (light-blue or green-blue) group constitutes of all the code in square parentheses but inner round parentheses.
4) the string data (brown) group is comprised of one-string declarations limited with single quotes or double quotes and a multi-string construction beginning with @’ and finishing at ‘@.
5) variable names (magenta) includes all unquoted string beginning with the $ sign and containing letters, numbers, underlines, question mark and colon. The dot is an end as well as the space.
6) specific words used within function declarations (bright blue). This groups the word function, and the function-related words param, begin, process, end inside curly brackets following the word function.
This color also can be used for statements like foreach, for, switch, if and so on.
7) function names (light lilac) of two types of occurrence: within the function declaration (that is, following the word function) and anywhere in the code. Function names usually contain letters, numbers and colons.
I hope that there is no need to repeat how lucky would be all WordPress Powershell bloggers if the WordPress developing team does the requested.
WordPress PowerShell Code Coloring Test
I have already written about how it’s possibly to post Powershell code here. As a year turned, why don’t check the state of affairs again?
My example is very simple and doesn’t cover all aspects of code. On the other hand, great sheets of code are not what is easily comparable with eyes.
1. This way my example is eyed in ISE:
Bugs are rare, however, it’s necessary to list them:
1.1 String data used without quotes is colored as a function (line 10)
1.2 Methods are not colored. It’s a typical trick, however, since nobody may know what it will be after the run of code. After having run the code, it’s considered here that no reason to re-color already colored code. (lines 10 and 42)
1.3 Property ‘Value’ is not colored (line 42).
Anyway, the coloring left the reader in a mood that all is healthy here.
2. Using Copy as HTML in PowerGUI 2.4 and Chrome 11, after adding manually line breaks (why doesn’t it type
s?), spaces and deleting trailing spaces after backticks (not in this sample), the following is workable:
cls #region WordPress posting code test #this is a test of Powershell code coloring [string]$stringVar1="string 1"; [string]$private:stringVar2='string 2'; [string]$script:stringVar3= @' string data '@ [scriptblock]$global:sb= {{Write-Hostscriptblock}.Invoke();}; function write1{Write-Host $stringVar1;} function private:write2 {param([string]$str2='')Write-Host $str2;} function script:write3 #this is a function { Write-Host$script:stringVar3; } function global:Print-SB { <# .SYNOPSIS This is a code coloring test. .DESCRIPTION This test function represents an advanced Powershell function syntax. .PARAMETER Param Demonstrates how a scriptblock can be passed as a reference. .EXAMPLE PS C:\> Print-SB ([ref]$sb) #> [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [ref]$Param ) Begin{} Process{$Param.Value.Invoke()} End{} } write1 private:write2 $private:stringVar2; script:write3 Print-SB ([ref]$global:sb) #endregion WordPress posting code test
2.1 In the second code snippet we have numerous problems with names of functions, both where they are declared and where they are called.
2.2 Write-Host inside the second function
2.3 Such stuff like attributes in an advanced function.
To conclude this section, use the Copy as HTML option is a choice if manual editing doesn’t fatigue you.
3. WordPress provides a set of tags. Several parameters might do the life of a codeblogger simpler, especially 'highlight'.cls #region WordPress posting code test #this is a test of Powershell code coloring [string]$stringVar1 = "string 1"; [string]$private:stringVar2 = 'string 2'; [string]$script:stringVar3 = @' string data '@ [scriptblock]$global:sb = {{Write-Host scriptblock}.Invoke();}; function write1{Write-Host $stringVar1;} function private:write2 {param([string]$str2 = '')Write-Host $str2;} function script:write3 #this is a function { Write-Host $script:stringVar3; } function global:Print-SB { <# .SYNOPSIS This is a code coloring test. .DESCRIPTION This test function represents an advanced Powershell function syntax. .PARAMETER Param Demonstrates how a scriptblock can be passed as a reference. .EXAMPLE PS C:\> Print-SB ([ref]$sb) #> [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [ref]$Param ) Begin{} Process{$Param.Value.Invoke()} End{} } write1 private:write2 $private:stringVar2; script:write3 Print-SB ([ref]$global:sb) #endregion WordPress posting code testHowever, the overall state is not appropriate, from my point of view. Yes, I know that the 'Frustration-Free' trademark is not WordPress's (as it is not Quest's too), but there is a room for improvement:
3.1 Variable names (lines 5, 6, 46, 48)
3.2 Function declarations and names (lines 11-13, 15, 21, 45-48)
3.3 A blob string (lines 7-9)
3.4 A specific to advanced functions comment-description (lines 23-35)
3.5 Types (lines 4-6, 10, 14)
3.6 Unquoted string (line 10)
I'll report these problems to Happiness engineers, maybe they share a bit of their happiness? 😉
PowerShell-disabled Areas On The Globe
A couple of weeks ago, I set the world-wide visitors widget (I love geography and maps). My blog is not a very popular place, being updated only from time to time, but the analysis is interesting.
From an independent point of view, examples of Winforms applications running in PowerShell should be equally interesting to people across the globe. However, it’s not so, far beyond from being so.
Let’s look at the coverage:
The US and Europe are undoubtedly global leaders. Western counties are the very center of PowerShell power, great and useful. Asia contributes too. Antipodes visit, but relatively rarely. The visitors are widespread across the US, whereas European ones are concentrated due to comparatively small sizes of their countries.
The most deserted areas like North Africa, Middle Asia, Western Australia and Greenland as well as South-American and African jungles are not supposed to hit the blog. The question here is Russia, with exception for Saint-Petersburg (my visits I suppose) it looks like a desert. Especially oddly does it seem like a Sahara in its European part. What may be the cause of this desertification effect? As I heard, some people in Moscow are aware of powershell advantages. Perhaps, the imperial tradition not to learn language but imperial one prevents guests from reading the blog? There is no answer, and never will be until Russian non-visitors explain such an evasion. 🙂
An Infinitesimal Update To ObjectBrowser
Hi, today’s update is really small.
– added a progress bar during the collecting Current AppDomain and GAC. This should do the GAC loading slightly less painful.
– the ability to be run from command line powershell as well as from ISE is now restored. Please use the following instruction to import the module:
Import-Module Add-on.PSDevStudioLite.ObjectBrowser -Force
Other changes relate to internal code structure and not to be seen right now in the GUI. As usual, the download location is here: http://www.box.net/shared/ot56ct7ngl




