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

Sticky Key problem between Windows Server 2012 and LogMeIn

This week I instructed my first class using Windows Server 2012 accessed via LogMeIn and discovered a Sticky Key problem every time you press the Shift key. Here is my solution to resolve this.  First off, in the Preferences of LogMeIn for the connection to the Windows Server, click General . Change the Keyboard and mouse priority to Host side user and click Apply at the bottom. On the Windows 2012 server, open the Control Panel – Ease of Access – Change how your keyboard works . Uncheck Turn on Sticky Keys . Click Set up Sticky Keys . Uncheck Turn on Sticky Keys when SHIFT is pressed five times . Click OK twice. If you are using Windows Server 2012 as a Hyper-V host, you will need to redo the Easy of Use settings on each guest operating system in order to avoid the Sticky Key Problem. Updated Information: March 20, 2013 If you continue to have problems, Uncheck Turn on Filter Keys .

Where did a User’s Account Get Locked Out?

Updated: May 15, 2015 When this article was originally published, two extra carriage returns were add causing the code to malfunction.  The code below is correct.   My client for this week’s PowerShell class had a really interesting question. They needed to know where an account is being locked out at. OK, interesting. Apparently users hop around clients and forget to log off, leading to eventual lock out of their accounts. The accounts can be unlocked, but are then relocked after Active Directory replication. This problem is solved in two parts. The first one is to modify the event auditing on the network. The second part is resolved with PowerShell. The first part involves creating a group policy that will encompass your Domain Controllers. In this GPO, make these changes. Expand Computer Configuration \ Policies \ Windows Settings \ Security Settings \ Advanced Audit Policy Configuration \ Audit Policies \ Account Management Double click User Account Management C...

Backup and Restore AD LDS with DSDBUTIL.exe

Active Directory Lightweight Directory Services allow you to create a directory service that allows applications to have access to user accounts, groups, and authentication similar to Active Directory Domain Services.  The big advantage here is that the schema of the directory service will not be bound by the rules of an Active Directory database.  Exchange 2007/2010, for example, use an instance of AD LDS on the Edge Transport Server to provide for user authentication from the internet.  Because your Active Directory database is not exposed to the internet, this is more secure. Applications will handle most of the dirty work should they require AD LDS.  You may want to make sure the database is being backed up and also have a restore plan in place.  Should the database become corrupt, the application that uses that database will fail.  This document will walk you through backing up and restoring an instance of AD LDS using the dsdbutil.exe command. Fi...