Skip to main content

How to Define a Datatype Using New-Variable

I feel a little bad on this one.  For those of you who have taken a PowerShell or Windows class with me, you know that I take notes on questions that I do not have a valid answer for.  I’m usually good at posting the answer after class on this blog.  Well, this is one left over from March so my bad on that one.  One reason is because I teach a lot and I am responsible for over 140 Sailors. The real reason…. I just figured it out.

So the question came up while we were talking about the formal declaration of variables using the cmdlet New-Variable.  Power shell allows you to create variables both ad-hoc, and formally.

# Ad-hoc creation of a variable.
$A1 = 100

# Formal creation
New-Variable -Name A2 -Value 200

Obviously the ad-hoc method is easier and I use it frequently.  I use the formal method for one of two reasons.  The first is if I want to provide a description of the variables intent.

# Provide a description of the variable.
New-Variable -Name B1 -Value "Hello" -Description "What I do"

# View the properties of the variable object.
Get-Variable -Name B1 | Select *

PS C:\> Get-Variable -Name B1 | Select *


PSPath        : Microsoft.PowerShell.Core\Variable::B1
PSDrive       : Variable
PSProvider    : Microsoft.PowerShell.Core\Variable
PSIsContainer : False
Name          : B1
Description   : What I do
Value         : Hello
Visibility    : Public
Module        :
ModuleName    :
Options       : None
Attributes    : {}

The other is if I want to create a constant instead of a variable.

# Create a constant.
New-Variable -Name C1 -Value 200 -Option Constant

# Read the variable.
$C1

# Attempt to change the value of the variable.
$C1 = 100

PS C:\> New-Variable -Name C1 -Value 200 -Option Constant

PS C:\> $C1
200

PS C:\> $C1 = 100
Cannot overwrite variable C1 because it is read-only or constant.
At line:1 char:1
+ $C1 = 100
+ ~~~~~~~~~
    + CategoryInfo          : WriteError: (C1:String) [], SessionStateUnauthorizedAccessException
    + FullyQualifiedErrorId : VariableNotWritable


PS C:\> 

The question that often arises is how to control the datatype of the variable.  If you give it a number it produces an object of System.Int32.

PS C:\> New-Variable -Name D1 -Value 100

PS C:\> $D1.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                  
-------- -------- ----                                     --------                                                                                                                   
True     True     Int32                                    System.ValueType  

If the value you provide is a decimal number, you will get an object of System.Double.

PS C:\> New-Variable -Name D2 -Value 100.1
$D2.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                  
-------- -------- ----                                     --------                                                                                                                   
True     True     Double                                   System.ValueType    

What if I wanted to create an object of System.Decimal?  This is the one that has eluded me.  So today I took a look at the documentation on System.Double. I took note of the first constructor and gave it a try.

PS C:\> [Decimal](100)
100

PS C:\> ([Decimal](100)).GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                  
-------- -------- ----                                     --------                                                                                                                  
True     True     Decimal                                  System.ValueType     

So I decided to provide this constructor to the –Value parameter of New-Variable.

New-Variable -Name E1 -Value [Decimal](100)

PS C:\> New-Variable -Name E1 -Value [Decimal](100)
New-Variable : A positional parameter cannot be found that accepts argument '100'.
At line:1 char:1
+ New-Variable -Name E1 -Value [Decimal](100)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Variable], ParameterBindingExc
   eption
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Command
   s.NewVariableCommand
 

This failed.  Look at the ISE colors.  Something is not right.  We need to have the constructor execute before the cmdlet so I encapsulated it inside of parenthesis.

New-Variable -Name E1 -Value ([Decimal](100))

Notice the colors are now correct.  Here is the result.

PS C:\> $E1
100

PS C:\> ($E1).GetType()

IsPublic IsSerial Name                                     BaseType                   
-------- -------- ----                                     --------                    
True     True     Decimal                                  System.ValueType    

It took a while. I just needed to figure out a new trick.


Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.