PowerShell variables, data types and objects

 

Basics of PowerShell variables and their data types.

Variables and data types

Variables can have different contents, e.g. a text, a number, a date or an object. To specify the type of content, data types are used, here is a small excerpt of known PowerShell data types:

Typ Description
[datetime] Date and time
[string] String (Text) String of any length.
[regex] Regular expression
[xml] XML document
[int] Integer with 32Bit length, negative and positive values

[float] und [single]

Number with decimal places (length 32bit)
[char] single character
[double] Number with decimal places (length 64bit)
[single] Single-precision floating number
[byte] Integer with 8Bit length: negative only (0 - 255)
[long] Integer negative and positive (64bit length)
[dezimal] Number with decimal places, 86Bit length
[bool] Yes-No values
[wmi] Windows Management Instrumentation (WMI object)
[wmiclass] WMI class
[adsi] Active Directory Services object
[wmiclass] WMI class
[wmisearcher] WMI search query
[adsi] Directory service object
[adsisearcher] LDAP search query in a directory service
[scriptblock] Powershell script block
[hashtable] Hash table: Name value of arbitrary objects
[psobject] PowerShell object
[type] Metadata for a class
... ...

Variables without type (untyped)

It is not mandatory to specify a data type, a variable can also be stored without a data type.

$x="1"

When $x is called, Powershell returns 1.

If the variable $x is called with a datatype, Powershell converts the variable to the respective datatype:

In the output, it makes no difference whether 1 is output as a number or as a text ...

Type to a value

A variable can be defined with the content of the data type number. $x = [int]"1"

$x was stored here with a number "1". In this case the number can be overwritten with a text (string):

$x="stringtext" would work, because the variable $x can be used for different data types:

Unlike the following example:

Type to a variable

If the variable is set to a specific data type, it cannot be overwritten with another type:

[int]$x = "1"

In this case the variable is made type "int". The variable can then only be used for numbers (int):

PS C:\Windows\system32> [int]$x="1"

PS C:\Windows\system32> $x="stringtext"
Cannot convert value "stringtext" to type "System.Int32". Error: "Input string 
was not in a correct format."
At line:1 char:1
+ $x="stringtext"
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetad 
   ataException
    + FullyQualifiedErrorId : RuntimeException
 

PS C:\Windows\system32> 

Cannot convert value "stringtext" to type "System.Int32". Error: "Input string was not in a correct format."

Only specific values:validateset

Only certain values can be allowed with validateset:

[validateset("1", "2", "3")][int]$x = "1"... works.

[validateset("1", "2", "3")][int]$x = "4"... is not allowed

The variable cannot be validated because the value 4 is not a valid value for the x variable.

Date

If variables with type datetime are used, PowerShell ISE (see: how to create a PowerShell script ) already suggests what is possible with this variable (properties and functions):

.AddDays, for example, can be used to simply add or subtract a certain number of days to the variable.

Deleting variables

The variable can be deleted again with the Remove-Variable command:

The alias for Remove-Variable is rv; alias, see: Function and terms

Single and double quotes

Variables inside double quotes (") are interpreted unless they are commented out with `. Variables inside single quotes (') are not interpreted.

PS C:\Windows\system32> $i="Variable"

PS C:\Windows\system32> "we use a $i"
we use a Variable

PS C:\Windows\system32> 'we use a $i'
we use a $i

PS C:\Windows\system32> "we use a `$i"
we use a $i

Input of variables by the user

[int]$x=read-host -prompt "please enter a number"

PS C:\Windows\system32> [int]$y=read-host -Prompt "please enter a number"
please enter a number: 4

PS C:\Windows\system32> $y
4

Objects-Members (GM)

Objects can also be stored in a variable. For example, get-service can be used to store a specific service in a variable:

$s=get-service -name wuauserv

The service, in our example wuauserv, is an object with certain properties and methods. A property could be the status of the service: started or stopped, a method to start or stop the service.

Using Get-Member or GM, all methods and properties of the object can then be output:

Pipe | to pass the variable to the Get-Member cmdlet. (Details about pipes are explained in more detail later in this article: PowerShell Syntax: compare and nest).

The members that are displayed can then be used with the variable, for example, "status".

$s.status

PS C:\Windows\system32> $s=get-service -name wuauserv
PS C:\Windows\system32> $s.Status
Running

with $s.start or $s.stop the service can be started or stopped:

Properties and methods of a variable within a variable

For a property of a variable to be applied inside a string, it must be interpreted as a variable and be inside $(....).

Sounds complicated, maybe the following example makes it clearer:

PS C:\Windows\system32> $message="this day: $($x.day)"
PS C:\Windows\system32> $message
this day: 20

without $(..) $x.day is interpreted like this:

$x without property and .day as text:

PS C:\Windows\system32> $message="this day: $x.day"
PS C:\Windows\system32> $message
this day: 01/20/2022 08:00:00.day

Variable with multiple objects

If a cmdlet is stored in a variable that contains multiple objects, the variable becomes an array:

$x calls all services, equivalent to typing get-service

$x[0] calls the first object of the array

$x[1] the second object

$x[-1]the last object

$x[0..3] calls the objects 1 to 4

$x.count counts all objects

$x[$x.count..0] for example calls all objects in reverse order:

Arrays are also described in the following article: Powershell Loops and Array

 

 

 

positive Bewertung({{pro_count}})
Rate Post:
{{percentage}} % positive
negative Bewertung({{con_count}})

THANK YOU for your review!

Questions / Comments


By continuing to browse the site, you agree to our use of cookies. More Details