PoshCode Archive  Artifact [c6c1ab7f35]

Artifact c6c1ab7f357b8ea8da0a02a03b530457d62a50d67da578ac510f6cfbf8dfa3be:

  • File Llist-context.ps1 — part of check-in [34abc4d7e0] at 2018-06-10 13:51:26 on branch trunk — Emulates Perl’s list context in PowerShell. (user: Public Domain size: 1445)

# encoding: ascii
# api: csharp
# title: Llist context
# description: Emulates Perl’s list context in PowerShell.
# version: 0.1
# type: class
# author: Public Domain
# license: CC0
# x-poshcode-id: 5176
# x-archived: 2014-05-24T12:31:16
# x-published: 2014-05-21T00:13:00
#
# This basically just converts $null to @() on assignment. PowerShell doesn’t need anything fancier than that because scalars will treated as an array with a single element in contexts that involve arrays.
#
<#

After you execute Add-Type, use it like:

[list()]$lhs = $rhs
# if $rhs is $null, $lhs will be @() instead.


This allows you to override PowerShell's sometimes annoying behavior of:

[object[]]$a = $null

treating $null as $null instead of an empty array via:

[object[]][list()]$a = $null

NOTE: Order matters. PowerShell evaluates attributes in order from RIGHT to LEFT.

#>


Add-Type -TypeDefinition @'
using System;
using System.Management.Automation;

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class ListAttribute : ArgumentTransformationAttribute {
	private static readonly object[] Value = new Object[0];

	public override Object Transform(EngineIntrinsics engineIntrinsics, Object inputData) {
		if (inputData == null || inputData == System.Management.Automation.Internal.AutomationNull.Value) {
			return ListAttribute.Value;
		}
		return inputData;
	}
}
'@