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

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.

How to run GPResult on a remote client with PowerShell

In the past, to run the GPResult command, you would need to either physically visit this client, have the user do it, or use and RDP connection.  In all cases, this will disrupt the user.  First, you need PowerShell remoting enabled on the target machine.  You can do this via Group Policy . Open PowerShell and type this command. Invoke-Command –ScriptBlock {GPResult /r} –ComputerName <ComputerName> Replace <ComputerName> with the name of the target.  Remember, the target needs to be online and accessible to you.

Error icon when creating a GPO Preference drive map

You may not have an error at all.  Take a look at the drive mapping below. The red triangle is what threw us off.  It is not an error.  It is simply a color representation of the Replace option of the Action field in the properties of the drive mappings. Create action This give you a green triangle. The Create action creates a new mapped drive for users. Replace Action The Replace action gives you a red triangle.  This action will delete and recreate mapped drives for users. The net result of the Replace action is to overwrite all existing settings associated with the mapped drive. If the drive mapping does not exist, then the Replace action creates a new drive mapping. Update Action The Update action will have a yellow triangle. Update will modify settings of an existing mapped drive for users. This action differs from Replace in that it only updates settings defined within the preference item. All other settings remain as configured on the ma...