PowerShell Commands for Everyday Usage

Rules For Every Script

Rule

Why

Start the script with a # Runs in: <feature> comment

Records which feature (Parameter Sync, Data Profile field, Properties panel, Script Tester...) the script was written for.

End the script with return <value>

Only the last value the script outputs is used as the result.

Return a simple value: text, a number, $true / $false, or $null

Revit objects (an ElementId, XYZ, Level...) are not valid results. Return a property such as .Name instead.

Wrap calls whose result you don't need in [void]

For example [void](Show-Message "Hi"). Otherwise their output can replace the script's result.

Don't create PowerShell functions or classes, and don't use Write-Host / Write-Output

Not supported in eVolve scripts. Console output is never shown, and Write-Output can replace the result.

Never change parameters or geometry, and never start a Transaction

The feature running the script writes the returned value. The only exception is a Generic Script Execution script run from the PowerShell Script Tester.

Variables

In PowerShell, variables serve as named containers for storing data values. They hold information that can be accessed and manipulated throughout a script or session. Variables are identified by a name that is preceded by a dollar sign ($).

Assign Variable

$var = "string"

Assign Multiple Variables

$a, $b = 'a', 'b' (different values)$a = $b = 0 (same value). Note that $a, $b = 0 sets $a to 0 and $b to $null.

Flip Variables

$a, $b = $b, $a

Strongly Typed Variable

[int]$var = 5 (the type goes on the left to lock the variable's type; $var = [int]5 only converts the value once)

Operators

Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators. Additionally, the + and * operators can also be used to work with strings. When you use the * operator, it repeats a string. When you use the + operator, it concatenates strings.

Assume integer variable A holds 40 and variable B holds 10, then...

Operator

Description

Example

+ (Addition)

Adds values on either side of the operator.

A + B = 50

- (Subtraction)

Subtracts the right-hand operand from the left-hand operand.

A - B = 30

* (Multiplication)

Multiplies values on either side of the operator.

A * B = 400

/ (Division)

Divides the left-hand operand by the right-hand operand.

B / A = 0.25

% (Modulus)

Divides left-hand operand by right-hand operand and returns the remainder.

B % A = 10

Comparison Operators

PowerShell comparison operators allow for comparing values and testing conditions. They are grouped into equality, matching, and containment operators. Case-sensitive operators can be indicated with a "c" (e.g., "-ceq"), while case-insensitive ones, which are the default, can be specified with an "i" (e.g., "-ieq").

Assume integer variable A holds 40 and variable B holds 10, then...

Operator

Description

Example

-eq (equals)

Compares two values to be equal or not.

A -eq B = false

-ne (not equals)

Compares two values to be not equal.

A -ne B = true

-gt (greater than)

Compares the first value to be greater than the second one.

B -gt A = false

-ge (greater than or equals to)

Compares the first value to be greater than or equal to the second one.

B -ge A = false

-lt (less than)

Compares the first value to be less than the second one.

B -lt A = true

-le (less than or equals to)

Compares the first value to be less than or equal to the second one.

B -le A = true

-like / -notlike (wildcard match)

Tests whether text matches a wildcard pattern (* = any characters, ? = one character).

"Pipe Elbow" -like "Pipe*" = true

-match (regular expression)

Tests whether text matches a regular expression.

"EMT-075" -match "\d+" = true

-contains (collection contains value)

Tests whether a list contains a value. The list goes on the left.

@(A, B) -contains 10 = true

-in (value is in collection)

Tests whether a value is in a list. The list goes on the right.

B -in @(10, 20) = true

Assignment Operators

In PowerShell, assignment operators are used to assign and modify values in variables. The equal sign (=) is the most common operator, assigning values to a variable and allowing for numeric operations before the assignment. The following are the assignment operators supported by PowerShell.

Operator

Description

Example

=

Simple assignment operator. Assigns values from the right side operands to the left side operand.

C=A+B will assign the value of A+B to C

+=

Add AND assignment operator. It adds the right operand to the left operand and assigns the result to the left operand.

C+=A is equivalent to C=C+A

-=

Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.

C-=A is equivalent to C=C-A

*=

Multiply AND assignment operator. It multiplies the left operand by the right operand and assigns the result to the left operand.

C*=A is equivalent to C=C*A

/=

Divide AND assignment operator. It divides the left operand by the right operand and assigns the result to the left operand.

C/=A is equivalent to C=C/A

%=

Modulus AND assignment operator. It divides the left operand by the right operand and assigns the remainder to the left operand.

C%=A is equivalent to C=C%A

Logical Operators

Logical operators in PowerShell are used to combine or invert the results of conditions. These operators are commonly utilized within if statements to control the flow of your script based on the conditions you set. By using logical operators, you can make your scripts more dynamic and responsive to various situations. The following table lists the logical operators.

Assume the boolean variable A is true and variable B is false, then...

Operator

Description

Example

-and (Logical and)

Called Logical AND operator. If both conditions are true, then the result is true.

(A -and B) is false

-or (Logical or)

Called Logical OR operator. If either condition is true, then the result is true.

(A -or B) is true

-not (Logical not)

Called Logical NOT operator. Reverses the logical state of its operand. If a condition is true then the Logical NOT operator will make it false.

-not (A -and B) is true

Misc Functions

Function

Description

Example

How to create a comment

Add a # in front of a line

#this is a commented line

How to comment out several lines

Wrap the lines in <# and #>

<# these linesare all comments #>

One-line if / else

Choose-Value <condition> <whenTrue> <whenFalse>

return Choose-Value ($length -gt 10) "Long" "Short"

Common Revit Functions

The table below lists sample scripts that when modified may help solve typical issues that users face when implementing PowerShell scripts. They use the built-in functions and context variables in eVolve Revit Plugins v9.4+, instead of raw LookupParameter() / Revit API calls.

Desired Function

PowerShell Script

Notes

Get Element Id

return $eVolveElement.Id.ToString()

$eVolveElement.Id is a Revit ElementId object, which is not a valid result. .ToString() returns the Id as text.

Get Instance Parameter

${name} = Get-ParameterValue "{ParamName}"

Replaces .LookupParameter("{ParamName}").AsString()/.AsDouble()/.AsInteger(). Get-ParameterValue returns the correctly-typed value automatically, and returns $null instead of an error when the parameter is missing.

Get Type Parameter

${name} = Get-ParameterValue "{ParamName}"

Get-ParameterValue checks instance first, then falls back to the type parameter. If an instance parameter has the same name, read the type explicitly:$elementType = $eVolveElement.Document.GetElement($eVolveElement.GetTypeId())${name} = Get-ParameterValue "{ParamName}" $elementType

Get MEP Length / Width / Height

return Get-MEPLengthreturn Get-MEPWidth -NominalSize

Works for pipe, duct, conduit, cable tray, fabrication parts and fittings. Returns decimal feet, or 0 if not applicable.

Get Level Name

return (Get-Level).Name

Replaces .LookupParameter("Level").AsValueString().

Convert to Decimal Inches

${name} = (Get-ParameterValue "ParamName") * 12

Leave off .ToString() to keep the result a number. For MEP lengths use (Get-MEPLength) * 12.

Rounding to nearest fraction

${name} = [Math]::Round($value * X) / X

$value = decimal feet, X = fractions per foot: 1/8" = 96, 1/4" = 48, 1/2" = 24, 1" = 12. The result is still decimal feet.

Format a value for display

return Get-RevitLengthDisplay (Get-MEPLength)return Get-RevitConduitSizeDisplay (Get-MEPWidth -NominalSize)

Formats using the project's units, such as 9' - 7 7/16" or 3/4". Also Get-RevitPipeSizeDisplay, Get-RevitDuctSizeDisplay, Get-RevitCableTraySizeDisplay, Get-RevitAngleDisplay.

Concatenate parameters and additional text

${name1} = Get-ParameterValue "{ParamName1}"${name2} = Get-ParameterValue "{ParamName2}"return "${name1} ${name2} additional text"

Split ValueString and return single word from specific position

$Example = $eVolveElement.LookupParameter("ExampleParam").AsValueString()return ($Example.Split(" "))[1]

The number in [ ] is the position of the word, starting at 0. For the value "EMT Compression Coupling" the example returns Compression. Don't write return $Example = ...: an assignment produces no output, so nothing is returned. .AsValueString() is used because Get-ParameterValue returns the underlying value, not the display text.

Get Location

return $eVolveElement.Location.Point.X (also .Y, .Z)$point = $eVolveElement.Location.Pointreturn "$($point.X), $($point.Y), $($point.Z)"

Location.Point is a Revit XYZ object, so return its parts or a text version. Values are decimal feet. Line-based elements (pipe, duct, conduit) have no Location.Point. Use $eVolveElement.Location.Curve.GetEndPoint(0) (start) or GetEndPoint(1) (end) instead.

Use a data table to lookup a value and return a separate value

${name1} = Get-ParameterValue "{ParamName}"${name2} = $eVolveData_{TableName}.Select("[{ColumnToCompare}]=${name1}")[0]["ColumnToReturn"]return ${name2}

Check if a string value returned from a data table is null or empty

if([String]::IsNullOrWhiteSpace($name)){return "Empty"}else{return "Not Empty"}

One-line version: return Choose-Value ([String]::IsNullOrWhiteSpace($name)) "Empty" "Not Empty"

How to get pi

$pi = [math]::pi

Data table lookup

$eVolveData_DATA_TABLE_NAME_HERE.Select("[SEARCH COLUMN]='$WHAT_TO_SEARCH'")[0]["RESULT COLUMN"]

Obtains the first search result found. If nothing matches, [0] causes an error. See "Data table lookup with no match" below.

Data table lookup with and

$eVolveData_DATA_TABLE_NAME_HERE.Select("[SEARCH COLUMN]='$WHAT_TO_SEARCH' and [SEARCH COLUMN2]='$WHAT_TO_SEARCH2'")[0]["RESULT COLUMN"]

Obtains the first search result found.

Data table lookup with no match

$rows = $eVolveData_DATA_TABLE_NAME_HERE.Select("[SEARCH COLUMN]='$WHAT_TO_SEARCH'")if ($rows.Count -eq 0) { return $null }return $rows[0]["RESULT COLUMN"]

Returns nothing instead of failing when no row matches.

Working with the connector manager

$connectedElements = Get-ConnectedElementsreturn $connectedElements.Count

Replaces manually walking $eVolveElement.ConnectorManager.Connectors. Returns the connected elements directly. The array itself is not a valid result, so return something from it such as .Count.

Element relationships

return (Get-NestedElements).Countreturn (Get-ContainedElements).Countreturn Test-IsAStraightreturn Test-IsNested

Nested elements; elements in a spool/assembly or group; whether the element is a straight (not a fitting); whether it is nested.

Reusable functions

Not supported

eVolve scripts don't support creating PowerShell functions or classes. If a need recurs often enough to want a reusable function, request it be added to eVolve's built-in library instead.

Abort (^abort^)

Returning the exact text "^abort^" cancels the script. What that does depends on the feature running it:

Feature

Effect of returning ^abort^

Parameter Sync

Values are left unchanged

Renumber

The item is not renumbered

Model Data Capture

The action is cancelled without submitting data

Data Profiles (field)

Processing stops for that field on all following items

Data Profiles (multiple column sourcing)

No columns are added for that element; later elements still run

Data Profiles (post-processing)

The data is left unmodified

Description Builder

An empty string is used instead

Selection Filter source

The filter selects nothing

Note: In a Data Profile field, ^abort^ does not hide just one value. It stops the field for the rest of the elements. To leave a single value blank there, return "" instead.

Testing Scripts

Use the PowerShell Script Tester ribbon command (eVolve Revit Plugins v10.4+) to run a script once and see the result. The default Single Value return type asks you to pick an element and shows the returned value; nothing is written to the model. $null shows as (null) and empty text as (empty text). A script error also shows as (empty text), with the error written only to the eVolve debug log.

Resolutions to common issues

Issue - I'd like to change the formatting of the displayed values.

Values in the Revit database are stored in imperial decimal feet; Revit then converts the stored values to the format set in Project Units. When the Use Display Value checkbox is selected in eVolve Data Profiles, the stored value is converted to the project's selected unit set. The issue arises when running a PowerShell script and the return value differs from the base parameter's type — e.g., if the base parameter type is text but the desired formatting for the return value is length, the formatting will only reflect that of a text parameter.

The solution is to select a base parameter of the same format type you'd like the return value displayed in, or use the matching Get-Revit*Display built-in (e.g. Get-RevitLengthDisplay, Get-RevitConduitSizeDisplay, Get-RevitPipeSizeDisplay) to format the value in the script and return text.

Issue - I'd like to display a window with information when a script runs.

Solution

# Runs in: <feature>
[void](Show-Message ("Value=" + $value))

Example

# Runs in: <feature>
$levelName = (Get-Level).Name
[void](Show-Message ("This is the Level: " + $levelName))
return $levelName

Show-Message replaces [System.Windows.Forms.MessageBox]::Show(...), and Get-Level replaces .LookupParameter("Level").AsValueString() for retrieving the level name. Show-Message outputs the button the user clicked, so wrap it in [void] to stop that replacing the script's result. The message box pauses Revit until it is closed, so use it for debugging only.

Issue - Always display parameters

Even though I have the Hide Empty Values option enabled, I would like to always display a parameter even if the value is null or empty.

Solution 1

# Runs in: <feature>
# Check to see if the parameter exists and the value is null or empty
if ([string]::IsNullOrWhiteSpace($eVolveFromParameter))
{
# Assigns a value if null or empty
return "Not Assigned"
}
# If the parameter exists and the value is not null or empty this defines the parameter to use
return $eVolveFromParameter

Solution 2

# Runs in: <feature>
# Check to see if the parameter exists and the value is null or empty
if ([string]::IsNullOrWhiteSpace($eVolveFromParameter))
{
# If the value is null or empty, "^abort^" is used to hide the parameter in the panel
return "^abort^"
}
# If the parameter exists and the value is not null or empty this defines the parameter to use
return $eVolveFromParameter

[string]::IsNullOrWhiteSpace() is used rather than -not $eVolveFromParameter, which also treats a value of 0 as empty. Do not use Solution 2 in a Data Profile field: there ^abort^ stops the field for all following elements (see Abort above).

Issue - Conditionally show parameters

I would like to conditionally show a parameter. For instance, I only want to display a parameter if the value is greater than 25.

Solution

# Runs in: <feature>
# $eVolveFromParameter can arrive as text, so convert it to a number before comparing
$value = 0.0
$isNumber = [double]::TryParse([string]$eVolveFromParameter, [ref]$value)

# Hide the parameter unless the value is a number greater than 25
if (-not $isNumber -or $value -le 25.0)
{
return "^abort^"
}
# The value is greater than 25, so show it
return $eVolveFromParameter

In a Data Profile field, return "" instead of "^abort^" (see Abort above).

Issue - Cycle through parameters to populate a single field

I would like to check if a parameter exists and if not use another parameter to populate the field. For example, I want to display the Reference Level in my panel, but when I select one element, the parameter name is "Reference Level" and when I select a different element it is "Level".

Solution 1

# Runs in: <feature>
# Check to see if the parameter exists and the value is null or empty
if ([string]::IsNullOrWhiteSpace($eVolveFromParameter))
{
# If the parameter is null or empty, use the level name instead
$level = Get-Level
if ($null -ne $level)
{
return $level.Name
}
return $null
}
# If the parameter exists and the value is not null or empty this defines the parameter to use
return $eVolveFromParameter

Solution 2

# Runs in: <feature>
# Defines the parameter to compare
$result = $eVolveFromParameter

# Check to see if the parameter exists and the value is null or empty
if ([string]::IsNullOrWhiteSpace($result))
{
# If the parameter is null or empty, fall back to the level name
$level = Get-Level
if ($null -ne $level)
{
$result = $level.Name
}
}
# Check to see if the value is still null or empty
if ([string]::IsNullOrWhiteSpace($result))
{
# If still null or empty, fall back to eV_PackageLevel
$result = Get-ParameterValue "eV_PackageLevel"
}
# If the parameter exists and the value is not null or empty this defines the parameter to use
return $result

Get-Level returns $null when the element has no associated level, so check it before reading .Name.

Issue - Round Numbers

The following solution allows the value to retain its number attribute without having to convert it to a string. Solution 1 returns a whole number. Solution 2 returns a decimal value by adding a comma and specifying the number of decimal places to return.

Solution 1

# Runs in: <feature>
${name} = Get-ParameterValue "{ParamName}"
return [math]::Round(${name})

If the original value were 12.87567894231564, the returned value would be 13.

Solution 2

# Runs in: <feature>
${name} = Get-ParameterValue "{ParamName}"
return [math]::Round(${name}, 3)

If the original value were 12.87567894231564, the returned value would be 12.876.

Note that a value exactly halfway rounds to the nearest even number by default (2.5 becomes 2, 3.5 becomes 4). To always round halves up, use [math]::Round(${name}, [System.MidpointRounding]::AwayFromZero).


How did we do?


Powered by HelpDocs (opens in a new tab)