Powershell Rapid Documentation

get-command | get-help | ConvertTo-Html -property Name, Synopsis > c:log2.html

Name Synopsis
Add-Content Adds content to the specified item(s).
Add-History Appends entries to the session history.
Add-Member Adds a user-defined custom member to an instance of a Windows PowerShell object.
Add-PathVariable PSCX Cmdlet: Adds the specified paths to the end of the named, path-oriented environment variable.
Add-PSSnapin Adds one or more Windows PowerShell snap-ins to the current console.
Clear-Content Deletes the contents of a item, such as deleting the text from a file, but does not delete the item.
Clear-Item Deletes the contents of an item, but does not delete the item.
Clear-ItemProperty Deletes the value of a property but it does not delete the property.
Clear-MSMQueue PSCX Cmdlet: Purges all messages from a queue
Clear-Variable Deletes the value of a variable.
Compare-Object Compares two sets of objects.
ConvertFrom-Base64 PSCX Cmdlet: Converts base64 encoded string to byte array.
ConvertFrom-SecureString Converts a secure string into an encrypted standard string.
Convert-Path Converts a path from a Windows PowerShell path to a Windows PowerShell provider path.
ConvertTo-Base64 PSCX Cmdlet: Converts byte array or specified file contents to base64 string.
ConvertTo-Html Creates an HTML page that represents an object or a set of objects.
ConvertTo-MacOs9LineEnding PSCX Cmdlet: Converts the line endings in the specified file to Mac OS9 and earlier style line endings “r”.
ConvertTo-SecureString Converts encrypted standard strings to secure strings. It can also convert plain text to secure strings. It is used with ConvertFrom-SecureString and Read-Host.
ConvertTo-UnixLineEnding PSCX Cmdlet: Converts the line endings in the specified file to Unix line endings “n”.
ConvertTo-WindowsLineEnding PSCX Cmdlet: Converts the line endings in the specified file to Windows line endings “rn”.
Convert-Xml PSCX Cmdlet: Performs XSLT transforms on the specified XML file or XmlDocument.
Copy-Item Copies an item from one location to another within a namespace.
Copy-ItemProperty Copies a property and value from a specified location to another location.
Disconnect-TerminalSession PSCX Cmdlet: Disconnects a specific remote desktop session on a system running Terminal Services/Remote Desktop
Expand-Archive PSCX Cmdlet: Expands a compressed archive file, or ArchiveEntry object, to its constituent file(s).
Export-Alias Exports information about currently-defined aliases to a file.
Export-Bitmap PSCX Cmdlet: Exports bitmap objects to various formats.
Export-Clixml Creates an XML-based representation of an object or objects and stores it in a file.
Export-Console Exports the configuration of the current console to a file so that you can reuse or share it.
Export-Csv Creates a comma-separated values (CSV) file that represents the input objects.
ForEach-Object Performs an operation against each of a set of input objects.
Format-Byte PSCX Cmdlet: Displays numbers in multiples of byte units.
Format-Custom Uses a customized view to format the output.
Format-Hex PSCX Cmdlet: Displays the contents of files or byte streams in hex format and optionally ASCII.
Format-List Formats the output as a list of properties in which each property appears on a new line.
Format-Table Formats the output as a table.
Format-Wide Formats objects as a wide table that displays only one property of each object.
Format-Xml PSCX Cmdlet: Pretty print for XML files and XmlDocument objects.
Get-Acl Gets the security descriptor for a resource, such as a file or registry key.
Get-ADObject PSCX Cmdlet: Search for objects in the Active Directory/Global Catalog.
Get-AdoConnection PSCX Cmdlet: Create an ADO connection to any database supported by .NET on the current machine. You can enumerate available ADO.NET Data Providers with the Get-AdoDataProvider Cmdlet.
Get-AdoDataProvider PSCX Cmdlet: List all registered ADO.NET Data Providers on the current machine.
Get-Alias Gets the aliases for the current session.
Get-AuthenticodeSignature Gets information about the Authenticode signature in a file.
Get-ChildItem Gets the items and child items in one or more specified locations.
Get-Clipboard PSCX Cmdlet: Gets data from the clipboard.
Get-Command Gets basic information about cmdlets and about other elements of Windows PowerShell commands.
Get-Content Gets the content of the item at the specified location.
Get-Credential Gets a credential object based on a user name and password.
Get-Culture Gets information about the regional settings on a computer.
Get-Date Gets the current date and time.
Get-DhcpServer PSCX Cmdlet: Gets a list of authorized DHCP servers.
Get-DomainController PSCX Cmdlet: Gets domain controllers.
Get-DriveInfo PSCX Cmdlet: Gets disk usage information on the system’s disk drives.
Get-EnvironmentBlock PSCX Cmdlet: Lists the environment blocks stored on the environment block stack.
Get-EventLog Gets information about local event logs or the entries stored in those event logs.
Get-ExecutionPolicy Gets the current execution policy for the shell.
Get-FileVersionInfo PSCX Cmdlet: Gets a FileVersionInfo object for the specified path.
Get-ForegroundWindow PSCX Cmdlet: Returns the hWnd or handle of the window in the foreground on the current desktop. See also Set-ForegroundWindow.
Get-Hash PSCX Cmdlet: Gets the hash value for the specified file or byte array via the pipeline.
Get-Help Displays information about Windows PowerShell cmdlets and concepts.
Get-History Gets a list of the commands entered during the current session.
Get-Host Gets a reference to the current console host object. Displays Windows Powershell version and regional information by default.
Get-HttpResource PSCX Cmdlet: Gets an HTTP resource or optionally the headers associated with the resource.
Get-Item Gets the item at the specified location.
Get-ItemProperty Retrieves the properties of a specified item.
Get-Location Gets information about the current working location.
Get-Member Gets information about objects or collections of objects.
Get-MountPoint PSCX Cmdlet: Returns all mount points defined for a specific root path.
Get-MSMQueue PSCX Cmdlet: Returns a list of all queues matching the filter parameters
Get-OpticalDriveInfo PSCX Cmdlet: Get information on optical drive capabilities on the local machine.
Get-PathVariable PSCX Cmdlet: Gets the specified path-oriented environment variable.
Get-PEHeader PSCX Cmdlet: Gets the Portable Header information from an executable file.
Get-PfxCertificate Gets information about .pfx certificate files on the computer.
Get-Privilege PSCX Cmdlet: Lists privileges held by the session and their current status.
Get-Process Gets the processes that are running on the local computer.
Get-PSDrive Gets information about Windows PowerShell drives.
Get-PSProvider Gets information about the specified Windows PowerShell provider.
Get-PSSnapin Gets the Windows PowerShell snap-ins on the computer.
Get-PSSnapinHelp PSCX Cmdlet: Generates a XML file containing all documentation data.
Get-Random PSCX Cmdlet: Returns a random number or a byte array.
Get-ReparsePoint PSCX Cmdlet: Gets NTFS reparse point data.
Get-Service Gets the services on the local computer.
Get-ShortPath PSCX Cmdlet: Gets the short, 8.3 name for the given path.
Get-TabExpansion PSCX Cmdlet: Gets matching tab expansions.
Get-TerminalSession PSCX Cmdlet: Gets information on terminal services sessions.
Get-TraceSource Gets the Windows PowerShell components that are instrumented for tracing.
Get-UICulture gets information about the current user interface culture for Windows PowerShell.
Get-Unique Returns the unique items from a sorted list.
Get-Variable Gets the variables in the current console.
Get-WmiObject Gets instances of WMI classes or information about available classes.
Group-Object Groups objects that contain the same value for specified properties.
Import-Alias Imports an alias list from a file.
Import-Bitmap PSCX Cmdlet: Loads bitmap files.
Import-Clixml Imports a CLIXML file and creates corresponding objects within Windows PowerShell.
Import-Csv Imports comma-separated value (CSV) files in the format produced by the Export-CSV cmdlet and returns objects that correspond to the objects represented in that CSV file.
Invoke-AdoCommand PSCX Cmdlet: Execute a SQL query against an ADO.NET datasource.
Invoke-Apartment PSCX Cmdlet:
Invoke-Expression Runs a Windows PowerShell expression that is provided in the form of a string.
Invoke-History Runs commands from the session history.
Invoke-Item Invokes the provider-specific default action on the specified item.
Join-Path Combines a path and child-path into a single path. The provider supplies the path delimiters.
Join-String PSCX Cmdlet: Joins an array of strings into a single string.
Measure-Command Measures the time it takes to run script blocks and cmdlets.
Measure-Object Measures characteristics of objects and their properties.
Move-Item Moves an item from one location to another.
Move-ItemProperty Moves a property from one location to another.
New-Alias Creates a new alias.
New-GenericObject PSCX Cmdlet: Creates objects from generic types using an easier syntax. NOTE: PowerShell V2 users can use PowerShell’s built-in New-Object cmdlet. In V2, it also supports an easier syntax for creating generic objects.
New-Hardlink PSCX Cmdlet: Creates filesystem hard links. The hardlink and the target must reside on the same NTFS volume.
New-Item Creates a new item in a namespace.
New-ItemProperty Sets a new property of an item at a location.
New-Junction PSCX Cmdlet: Creates NTFS directory junctions.
New-MSMQueue PSCX Cmdlet: Creates a new queue object with the defined properties
New-Object Creates an instance of a .Net or COM object.
New-PSDrive Installs a new WIndows PowerShell drive.
New-Service Creates a new entry for a Windows Service in the registry and the Service Database.
New-Shortcut PSCX Cmdlet: Creates shell shortcuts.
New-Symlink PSCX Cmdlet: Creates filesystem symbolic links. Requires Microsoft Windows Vista or later.
New-TimeSpan Creates a TimeSpan object.
New-Variable Creates a new variable.
Out-Clipboard PSCX Cmdlet: Formats text via Out-String before placing in clipboard.
Out-Default Send the output to the default formatter and the default output cmdlet. This cmdlet has no effect on the formatting or output. It is a placeholder that lets you write your own Out-Default function or cmdlet.
Out-File Sends output to a file.
Out-Host Sends output to the command line.
Out-Null Deletes output instead of sending it to the console.
Out-Printer Sends output to a printer.
Out-String Sends objects to the host as a series of strings.
Ping-Host PSCX Cmdlet: Sends ICMP echo requests to network hosts.
Pop-EnvironmentBlock PSCX Cmdlet: Pops the topmost environment block.
Pop-Location Changes the current location to the location most recently pushed onto the stack. You can pop the location from the default stack or from a stack that you create by using Push-Location.
Push-EnvironmentBlock PSCX Cmdlet: Pushes the current environment onto the environment block stack.
Push-Location Pushes the current location onto the stack.
Read-Archive PSCX Cmdlet: Enumerates compressed archives such as 7z or rar, emitting ArchiveEntry objects representing records in the archive.
Read-Host Reads a line of input from the console.
Receive-MSMQMessage PSCX Cmdlet: Receives the first message available in the queue. This call is synchronous, and blocks the current thread of execution until a message is available.
Remove-Item Deletes the specified items.
Remove-ItemProperty Deletes the property and its value from an item.
Remove-MountPoint PSCX Cmdlet: Removes a mount point, dismounting the current media if any. If used against the root of a fixed drive, removes the drive letter assignment.
Remove-PSDrive Removes a Windows PowerShell drive from its location.
Remove-PSSnapin Removes Windows PowerShell snap-ins from the current console.
Remove-ReparsePoint PSCX Cmdlet: Removes NTFS reparse junctions and symbolic links.
Remove-Variable Deletes a variable and its value.
Rename-Item Renames an item in a Windows PowerShell provider namespace.
Rename-ItemProperty Renames a property of an item.
Resize-Bitmap PSCX Cmdlet: Resizes bitmaps.
Resolve-Assembly PSCX Cmdlet: Resolve and optionally import Assemblies by partial name with optional Version.
Resolve-Host PSCX Cmdlet: Resolves host names to IP addresses.
Resolve-Path Resolves the wildcard characters in a path and displays the path contents.
Restart-Service Stops and then starts one or more services.
Resume-Service Resumes one or more suspended (paused) services.
Scroll-Table PSCX Cmdlet: An object oriented “pager” for PowerShell. Designed as an interactive replacement of Format-Table and Format-List. Press ? or h inside to get keyboard help.
Scroll-Text PSCX Cmdlet: A less-like pager for Windows Powershell. Press ? or h inside to get keyboard help.
Select-Object Selects specified properties of an object or set of objects. It can also select unique objects from an array of objects or it can select a specified number of objects from the beginning or end of an array of objects.
Select-String Identifies patterns in strings.
Select-Xml PSCX Cmdlet: Select elements in XML files and XmlDocument objects with XPath expressions.
Send-MSMQMessage PSCX Cmdlet: Wraps an object in a Message, and places it onto the defined queue.
Send-SmtpMail PSCX Cmdlet: Sends email via specified SMTP server to specified recipients.
Set-Acl Changes the security descriptor of a specified resource, such as a file or a registry key.
Set-Alias Creates or changes an alias (alternate name) for a cmdlet or other command element in the current Windows PowerShell session.
Set-AuthenticodeSignature Uses an authenticode signature to sign a Windows PowerShell script or other file.
Set-Clipboard PSCX Cmdlet: Puts the specified object into the system clipboard.
Set-Content Writes or replaces the content in an item with new content.
Set-Date Changes the system time on the computer to a time that you specify.
Set-ExecutionPolicy Changes the user preference for the execution policy of the shell.
Set-FileTime PSCX Cmdlet: Sets a file or folder’s created and last accessed/write times.
Set-ForegroundWindow PSCX Cmdlet: Given an hWnd or window handle, brings that window to the foreground. Useful for restoring a window to uppermost after an application which seizes the foreground is invoked. See also Get-ForegroundWindow
Set-Item Changes the value of an item to the value specified in the command.
Set-ItemProperty Sets the value of a property at the specified location.
Set-Location Sets the current working location to a specified location.
Set-PathVariable PSCX Cmdlet: Sets the specified path-oriented environment variable.
Set-Privilege PSCX Cmdlet: Adjusts privileges associated with a user (identity).
Set-PSDebug Turns script debugging features on and off, sets the trace level and toggles strict mode.
Set-Service Changes the display name, description, or starting mode of a service.
Set-TraceSource Configures, starts, and stops a trace of Windows PowerShell components.
Set-Variable Sets the value of a variable. Creates the variable if one with the requested name does not exist.
Set-VolumeLabel PSCX Cmdlet: Modifies the label shown in Windows Explorer for a particular disk volume.
Skip-Object PSCX Cmdlet: Skips the specified objects in the pipeline.
Sort-Object Sorts objects by property values.
Split-Path Returns the specified part of a path.
Split-String PSCX Cmdlet: Splits a single string into an array of strings.
Start-Process PSCX Cmdlet: Starts a new process.
Start-Service Starts one or more stopped services.
Start-Sleep Suspend shell, script, or runspace activity for the specified period of time.
Start-TabExpansion PSCX Cmdlet: Initializes the tab expansion caches.
Start-Transcript Creates a record of all or part of a Windows PowerShell session in a text file.
Stop-Process Stops one or more running processes.
Stop-Service Stops one or more running services.
Stop-TerminalSession PSCX Cmdlet: Logs off a specific remote desktop session on a system running Terminal Services/Remote Desktop
Stop-Transcript Stops a transcript.
Suspend-Service Suspends (pauses) one or more running services.
Tail-File PSCX Cmdlet: Tails the contents of a file – optionally waiting on new content.
Tee-Object Pipes object input to a file or variable, then passes the input along the pipeline.
Test-Assembly PSCX Cmdlet: Tests whether or not the specified file is a .NET assembly.
Test-MSMQueue PSCX Cmdlet:
Test-Path Determines whether all elements of a path exist.
Test-Scroll PSCX Cmdlet:
Test-UserGroupMembership PSCX Cmdlet: Tests whether or not a user (current user by default) is a member of the specified group name.
Test-Xml PSCX Cmdlet: Tests for well formedness and optionally validates against XML Schema.
Trace-Command The Trace-Command cmdlet configures and starts a trace of the specified expression or command.
Update-FormatData Updates and appends format data files.
Update-TypeData Updates the current extended type configuration by reloading the *.types.ps1xml files into memory.
Where-Object Creates a filter that controls which objects will be passed along a command pipeline.
Write-BZip2 PSCX Cmdlet: Create BZIP2 format archive files from pipline or parameter input.
Write-Clipboard PSCX Cmdlet: Writes objects to the clipboard using their string representation, bypassing the default PowerShell formatting.
Write-Debug Writes a debug message to the host display.
Write-Error Writes an object to the error pipeline.
Write-GZip PSCX Cmdlet: Create GNU ZIP (GZIP) format files from pipeline or parameter input.
Write-Host Displays objects by using the host user interface
Write-Output Writes objects to the success pipeline.
Write-Progress Displays a progress bar within a Windows PowerShell command window.
Write-Tar PSCX Cmdlet: Create Tape Archive (TAR) format files from pipeline or parameter input.
Write-Verbose Writes a string to the verbose display of the host.
Write-Warning Writes a warning message.
Write-Zip PSCX Cmdlet: Create ZIP format archive files from pipline or parameter input.

Powershell PSCX ado sample

$Provider=”System.Data.SQLClient”
$ConnectionString=”Data Source=.;Initial Catalog=Northwind;Integrated Security=SSPI”
$Connection = Get-AdoConnection $Provider $ConnectionString
$Query = “SELECT * FROM Orders”

Invoke-AdoCommand -ProviderName $Provider -Connection $Connection -CommandText $Query

$Connection.Close()

NVelocity

This is a simple templating tool.

Here is the documentation for the templates.

This is what you need to get NVelocity to work:

NVelocity.Context.IContext context = new VelocityContext();

context.Put(“name”, “Chris”);

NVelocity.Runtime.RuntimeSingleton.Init();
NVelocity.Template template = NVelocity.Runtime.RuntimeSingleton.GetTemplate(“helloworld.vm”);

StringWriter writer = new StringWriter();

template.Merge(context, writer);

Console.WriteLine(writer.ToString());

Here  is the template:

Hello $name!  Welcome to Velocity!

Service Locators versus Inversion of Control Conatiners

Of late I have been using “service locator” similar to the below:

//=== class ServiceLocator ====

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
using System.Xml;

namespace PerfectStorm
{
/// <summary>
/// This is used to allow the creation of a class to be decoupled from the implementation.
/// The client only needs to know the name and have a supported interface or base class.
///
/// The only restriction this imposes on the created class is that it must have an empty
/// constructor.
///
/// The registry may be populated automatically from the appropriate config file or the
/// client may populate it itself.  By default the full name of the class is used, but
/// if client-populated then any unique string identifier will do.
///
/// The beauty of this clarity of split is that the caller may not know any of the
/// implementation details. This ensures that the implementation can be replaced only
/// requiring a configuration setting.
///
/// </summary>
public static class ServiceLocator
{
static Dictionary<string, Type> _dict = new Dictionary<string, Type>();

// This will be called before the first method on the type.
static ServiceLocator()
{
XmlNode configNode = (XmlNode)ConfigurationManager.GetSection(“PerfectStorm.ServiceLocator”);
if (configNode != null)
{
foreach (XmlNode node in configNode.SelectNodes(“//PerfectStorm.ServiceLocator/assembly”))
{
LoadAssembly(node.Attributes[“name”].InnerText);
}
}
}

/// <summary>
///
/// </summary>
/// <param name=”Name”></param>
public static void LoadAssembly(string Name)
{
Assembly a = Assembly.Load(“Name”);
Type[] types = a.GetTypes();
foreach (Type t in types)
{
if (!t.IsAbstract)
{
// Only add if can be constructed.
if (t.GetConstructor(System.Type.EmptyTypes) != null)
{
AddType(t.FullName, t);
}
}
}

}

/// <summary>
/// Creates an instance of a named class that conforms to the supplied interface or base type.
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <param name=”name”></param>
/// <returns></returns>
public static T CreateInstance<T>(string name)
{
Type t = null;
if (_dict.ContainsKey(name))
{
t = _dict[name];
}
else
{
throw new Exception(string.Format(“ServiceLocator is Unable to create {0}”, name));
}

return (T)Activator.CreateInstance(t);
}

/// <summary>
///
/// </summary>
/// <typeparam name=”T”></typeparam>
/// <remarks>Can only register classes with parameterless constructors.</remarks>
public static void Register<T>() where T : new()
{
Type type = typeof(T);
AddType(type.FullName, type);
}

/// <summary>
///
/// </summary>
/// <param name=”Name”></param>
/// <param name=”T”></param>
private static void AddType(string Name, Type T)
{
if (_dict.ContainsKey(Name))
{
_dict[Name] = T;
}
else
{
_dict.Add(Name, T);
}
}

/// <summary>
/// Empties the registry.
/// </summary>
/// <remarks>This has been included to assist unit testing.</remarks>
public static void Clear()
{
_dict.Clear();
}
}
}

This allows applications to load an assembly based upon config.

You will also need the Trivial section handler:

using System;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;

namespace PerfectStorm
{
/// <summary>
/// This allows the config section to be read as an XML node.
/// </summary>
/// <remarks>
/// This is identical code to that used in PerfectStorm.CodeGenLibrary but I don’t want to cause
/// a dependency between the two.
/// </remarks>
public class ServiceLocatorConfig : IConfigurationSectionHandler
{
/// <summary>
///
/// </summary>
/// <param name=”parent”></param>
/// <param name=”configContext”></param>
/// <param name=”section”></param>
/// <returns></returns>
public object Create(
object parent,
object configContext,
System.Xml.XmlNode section)
{
// This was based upon an idea that I got from:
// (http://alt.pluralsight.com/wiki/default.aspx/Craig/XmlSerializerSectionHandler.html)
return section;
}
}

}

This permit usages based upon config such as:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<configSections>
<section name=”PerfectStorm.ServiceLocator” type=”PerfectStorm.ServiceLocatorConfig, PerfectStorm.ServiceLocator” />
</configSections>
<PerfectStorm.ServiceLocator>
<assembly name=”My fully qualified name” />
</PerfectStorm.ServiceLocator>
</configuration>

This permits the use:

IYourInterface svc = ServiceLocator.CreateInstance<IYourInterface>(“fully qualified name of class”);

This means that the caller and implementer only need agree on the interface and everything else can be setup in config.

This has allowed me to make rapid changes to the architecture of an application (in one case to break a cyclic dependency and in another to replace a set of pointless local WCF calls with a call to an interface.  This has been easy to retrofit to an existing application – probably because we have been working through some narrow interfaces (that is almost all remote calls went through one of three interfaces).  I have found it useful to move the interfaces into a common assembly providing the service interfaces.

The only limitation of the ServiceLocator is that the classes created require a parameterless constructor.

I have started looking at Winsor (from the Castle project) as an alternative.

The following is a usage sample of Winsor:

using System;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using TestLib;

namespace TestProject
{
class Program
{
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer(new XmlInterpreter());
IExecutor service = container.Resolve<IExecutor>();

// Or to be specific IExecutor service = container.Resolve<IExecutor>(“test”);

service.Execute();
Console.ReadLine();
}
}
}

This was controlled by the following config file:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<configSections>
<section
name=”castle”
type=”Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor” />
</configSections>

<castle>

<components>
<component id=”test”
service=”TestLib.IExecutor, TestLib”
type=”TestLibImplementation.Executor2, TestLibImplementation” />
</components>

</castle>
</configuration>

There is no reason why you can’t alter Winsor to use reflection to get all types from an assembly (in fact Binsor frequently does this).

Now this is very similar to the above Service Locator (With the right id name the usage would be identical).

I have more investigation of Winsor to do…

Use of Third Party Applications/Code in yours

Quite often you need to use a third party application in your code.  This may be a workflow tool, a reporting service.

If you need to integrate with it  (you need to call it or it needs to call you) keep these to a small well defined interface.

Build a simple assembly for calling it an use that for all access.  For it to call you produce a second small assembly.

Do not let any of it’s implementation details leak beyond that.  Those should be the only assemblies that have a reference to the third party code.

Careful use of this can allow you to replace a product (possibly with some custom code) at a later time with minimal effort.