Типы данных power shell

This lesson introduces PowerShell variables, constants, and data types.

After completing this lesson, you will be able to:

  • Explain basic concepts regarding variables.
  • Describe the difference between variables and constants.
  • Understand data types and type conversions.
  • Use variables to capture user input and use that input later in script output.
# This script demonstrates the difference between numeric and string data types.

    
                # Displays 2
      # Displays Int32

    
                # Displays 11
      # Displays String

Variables may be cast from one type to another by explicit conversion.

# This script demonstrates data types and data type conversion.

  

              # Displays 1.9
       # Displays 2
       # Displays 1.9
      # Displays 1.9
     # Displays True
    
# This script demonstrates the difference between single quotes and double quotes.

  '$(1 + 2)'
    

     # Displays $(1 + 2)
     # Displays 3
   'Is it morning, afternoon, or evening? '
 
  1. Review Microsoft TechNet: Get-Variable and Microsoft TechNet: about_Automatic_Variables. Start a new PowerShell session and use Get-Variable to display a list of all automatic variables and values that are defined by default when a new session is started.
  2. Review Microsoft TechNet: Using the Read-Host Cmdlet. Write a script that asks the user to enter their name, and then display a greeting back to the user that includes their name, such as ‘Hello Wikiversity!’. Add a comment at the top of the script that describes the purpose of the script.
  3. Review Microsoft TechNet: about_Quoting_Rules. Experiment with the Hello script above using both using single quotes and double quotes to display the strings to ensure that you understand the difference between the two.
  4. Review Windows IT Pro: Working with PowerShell’s Data Types. Experiment with entering different types of data (integers, floating point values, dates, strings) and use GetType() to display the data type entered.
  5. Review PowerShell.cz: Explicit Type Casting Versus Strongly Typed Variables. Experiment with data type conversion (type casting) and strongly typed variables when entering different types of data.
  • A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.[5]
  • A constant is an identifier whose associated value cannot typically be altered by the program during its execution.[6]
  • Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.[7]
  • In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.[8]
  • A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.[9]
  • Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.[10]
  • The scope of a variable describes where in a program’s text the variable may be used, while the extent (or lifetime) describes when in a program’s execution a variable has a (meaningful) value.[11]
  • Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations — such as code block, function, or module — in between. [12]
  • In PowerShell, a variable name always begins with a dollar sign ($).[13]
  • PowerShell variable names are not case sensitive.[14]
  • The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.[15]
  • PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.
  • Variables may be converted from one type to another by explicit conversion, such as [int32]$value.
  • In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.[16]
  • The Read-Host cmdlet reads a line of input from the console.[17]
ASCII (American Standard Code for Information Interchange)
A character-encoding scheme originally based on the English alphabet that encodes 128 specified characters – the numbers 0-9, the letters a-z and A-Z, some basic punctuation symbols, some control codes that originated with Teletype machines, and a blank space – into 7-bit binary integers.[18]
bit
A binary digit, having only two possible values most commonly represented as 0 and 1.[19]
Boolean
A data type with only two possible values: true or false.[20]
byte
A unit of digital information in computing and telecommunications that most commonly consists of eight bits, representing the values 0 through 255.[21]
character
A unit of information that roughly corresponds to a symbol , such as in an alphabet in the written form of a natural language.[22]
floating-point
A method of representing an approximation of a real number in a way that can support a wide range of values based on a fixed number of significant digits which are scaled using an exponent.[23]
garbage collection
A form of automatic memory management in which the garbage collector attempts to reclaim memory occupied by objects that are no longer in use by the program.[24]
immutable
An object whose state or value cannot be modified after it is created.[25]
integer
A data type which represents some finite subset of whole numbers, such as -32,768 to 32,767.[26][27]
memory leak
Incorrect management of memory allocation by a program, resulting in a reduction of available memory for running applications.[28]
string
A data type which represents a sequence of characters, either as a literal constant or as some kind of variable.[29]
Unicode
A computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world’s writing systems, in which a single character may be represented by one, two, or four bytes, depending on the character set and encoding used.[30]

Enable JavaScript to hide answers.

Click on a question to see the answer.

1.
A variable or scalar is _____.

A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.

2.
A constant is _____.

A constant is an identifier whose associated value cannot typically be altered by the program during its execution.

3.
Many programming languages employ a reserved value (often named _____) to indicate an invalid or uninitialized variable.

Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.

4.
In almost all languages, variable names cannot start with _____ and cannot contain _____.

:/>  Какие обновления нельзя устанавливать в операционной системе Windows 7 x64.: spayte — LiveJournal

In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.

5.
A data type or simply type is _____ that determines _____, _____, _____, and _____.

A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.

6.
Type conversion, typecasting, and coercion are _____.

Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.

7.
The scope of a variable describes _____, while the extent (or lifetime) describes _____.

The scope of a variable describes where in a program’s text the variable may be used, while the extent (or lifetime) describes when in a program’s execution a variable has a (meaningful) value.

8.
Scope can vary from as little as _____ to as much as _____, with many possible gradations — such as _____ in between.

9.
In PowerShell, a variable name always begins with _____.

In PowerShell, a variable name always begins with a dollar sign ($).

10.
PowerShell variable names _____ case sensitive.

PowerShell variable names are not case sensitive.

11.
The assignment operator _____. You can assign almost anything to a variable, even _____.

The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.

12.
PowerShell data types include _____.

PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.

13.
Variables may be converted from one type to another by _____.

14.
In Windows PowerShell, single quotes display literal strings _____. Double quotes _____.

In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.

15.
The Read-Host cmdlet _____.

The Read-Host cmdlet reads a line of input from the console.

For example if I search for Smith it would return:

[0] Smith, John   jsmith
[1] Smith, Jane   jsmith1
[2] Smithfield, Robert  rsmithfield

The tech would then need to enter the corresponding number of the account they want to modify. I put in an input validation check to ensure that a valid index number is chosen (in this case it will not accept a negative int or an int greater than 2).

How do I make it so it will only accept an int?

FYI – after I get this working I will be creating functions and function calls so it would be more modular, this is just initial testing of the concept.

#prompt for last name (or at least portion of last name, then conver to a string with wild card for use in filter
$lname = Read-Host "`nEnter at least the first three chars of users last name (you may enter full last name)"
$search = $lname + "*"

#Empty arrays
$ResultsArray=@("")
$ADUsersList=@("")

#add aduser properties to array, return error and exit if no user found
$ADUsersList += Get-ADUser -filter 'surname -like $search' -Properties * | select name,samaccountname,DistinguishedName
if ($ADUsersList.count -le 1){
    Write-host "USER NOT FOUND"
    return
}

#populate a 2D array with NAM and with UserID
$ResultsArray = @(($ADUsersList.name),($ADUsersList.samaccountname))

#return list of found users and user ids. Preface with index number to use for selection menu
for($i=0;$i-le $ResultsArray[0].length-1;$i++){
    “[{0}] = {1} `t {2}” -f $i,$ResultsArray[0][$i],$ResultsArray[1][$i]
}

#Prompt 
[int]$selection = Read-Host "`nEnter number for user you want to modify"

#Input validation - Only allow a valid index #.  If valid, write user selected to screen before proceeding 
if ($selection -gt $ResultsArray[0].length -or $selection -lt 0){
    Write-host "INVALID SELECTION!!!" -ForegroundColor Red
} 
else {
    Write-Host "`nYou selected user " -nonewline 
    Write-Host $ResultsArray[0][$selection] -nonewline -ForegroundColor Green
    Write-Host " with user ID a of " -nonewline 
    Write-Host $ResultsArray[1][$selection] -nonewline -ForegroundColor Green
}

If you are starting PowerShell and want to become an expert in it, you should have a complete understanding of PowerShell data types. In this PowerShell tutorial, I will show you various data types in PowerShell, including integers, floats, doubles, decimals, characters, strings, Booleans, dates, arrays, hash tables, and custom objects.

I will also show you how to check the data type in PowerShell.

Various Data Types in PowerShell

Here are a few data types in PowerShell with examples.

1. Integer

Syntax

[int]$integerVariable = 10

Examples

Here is a complete example.

[int]$positiveInteger = 42
[int]$negativeInteger = -42

# Arithmetic operations
$sum = $positiveInteger + $negativeInteger
Write-Output $sum

You can see the output in the screenshot below:

Data Types in PowerShell

2. Float and Double

Syntax

Here is the syntax for float and double data types in PowerShell.

[float]$floatVariable = 10.5
[double]$doubleVariable = 10.5

Examples

Here is an example.

[float]$floatNumber = 3.14
[double]$doubleNumber = 3.141592653589793

# Arithmetic operations
$floatSum = $floatNumber + 2.86
$doubleSum = $doubleNumber + 2.86
Write-Output $floatSum  # Output: 6.00000010490417
Write-Output $doubleSum  # Output: 6.001592653589793

When I executed the script using VS code and the output, you can see the output in the screenshot below:

PowerShell Data Types

3. Decimal

Syntax

Here is the syntax for decimal data types in PowerShell.

[decimal]$decimalVariable = 10.5

Examples

Here is an example.

[decimal]$decimalNumber = 123.4567890123456789012345678

# Arithmetic operations
$decimalSum = $decimalNumber + 0.5432109876543210987654321
Write-Output $decimalSum 

Read How to Handle Errors with Try-Catch in PowerShell?

4. Character

Syntax

Here is the syntax of character data type in PowerShell.

[char]$charVariable = 'A'

Examples

[char]$charA = 'A'
[char]$charB = 'B'

# Concatenation
$charConcat = "$charA$charB"
Write-Output $charConcat

You can see the output in the screenshot below:

PowerShell data types examples

5. String

Syntax

Here is the syntax:

[string]$stringVariable = "Hello, World!"

Examples

Here is an example.

[string]$greeting = "Hello"
[string]$name = "World"

# String concatenation
$fullGreeting = "$greeting, $name!"
Write-Output $fullGreeting  # Output: Hello, World!

# String length
$stringLength = $fullGreeting.Length
Write-Output $stringLength  # Output: 13

6. Booleans

Syntax

Here is the syntax for booleans of data types in PowerShell.

[bool]$booleanVariable = $true

Examples

Here is a simple example of how to use boolean data types in PowerShell.

[bool]$isTrue = $true
[bool]$isFalse = $false

# Conditional check
if ($isTrue) {
    Write-Output "This is true."
} else {
    Write-Output "This is false."
}

I executed the above PowerShell script, and you can see the output in the screenshot below:

boolean data types in PowerShell

7. Dates

Syntax

Here is the syntax

[datetime]$dateVariable = Get-Date

Examples

Here is an example.

[datetime]$currentDate = Get-Date
Write-Output $currentDate  # Output: Current date and time

# Specific date
[datetime]$specificDate = [datetime]"2024-01-01"
Write-Output $specificDate  # Output: 01 January 2024 00:00:00

8. Arrays

Syntax

Here is the syntax:

[array]$arrayVariable = @(1, 2, 3, 4, 5)

Examples

Here is a simple example of how to use the array data type in PowerShell.

[array]$numbers = @(1, 2, 3, 4, 5)
Write-Output $numbers  # Output: 1 2 3 4 5

# Accessing elements
$firstNumber = $numbers[0]
Write-Output $firstNumber  # Output: 1

# Adding elements
$numbers += 6
Write-Output $numbers  # Output: 1 2 3 4 5 6

9. Hash Tables

Syntax

Here is the syntax:

$hashTable = @{ Key1 = 'Value1'; Key2 = 'Value2' }

Examples

Here is a complete example of how to use the hashtable data type in PowerShell.

$person = @{
    Name = "John"
    Age = 30
    Occupation = "Developer"
}

# Accessing values
$name = $person["Name"]
Write-Output $name  # Output: John

# Adding key-value pairs
$person["Country"] = "USA"
Write-Output $person

You can see the output in the screenshot below:

powershell data type hashtable

10. Custom Objects

Syntax

Here is the syntax of custom objects data type in PowerShell.

$customObject = New-Object PSObject -Property @{
    Property1 = 'Value1'
    Property2 = 'Value2'
}

Examples

Here is a simple example to understand about the PowerShell custom objects data type.

$person = New-Object PSObject -Property @{
    Name = "Jane"
    Age = 28
    Occupation = "Designer"
}

# Accessing properties
Write-Output $person.Name  # Output: Jane

# Adding properties
$person.Country = "Canada"
Write-Output $person 

How to Check Data Type in PowerShell?

Now, let me show you how to check data type in PowerShell with a few examples.

:/>  Как проверить пинг интернета через командную строку. Тестирование работы сети

In PowerShell, you can determine the data type of a variable by using the GetType() method. This method provides detailed information about the variable type, such as its name and base type. Here’s how you can use it:

  1. Assign a value to a variable:$x = 10
  2. Use the GetType() method to find out the type:$x.GetType()

Here are a few examples to understand this better.

Example 1: Integer Type

The below PowerShell script is to know about the integer type in PowerShell.

$x = 10
$xType = $x.GetType()
Write-Output $xType
IsPublic IsSerial Name     BaseType
-------- -------- ----     --------
True     True     Int32    System.ValueType

In this example, $x is of type Int32, which is an integer.

Example 2: String Type

Here is an example for a string data type in PowerShell.

$str = "Hello, PowerShell!"
$strType = $str.GetType()
Write-Output $strType
IsPublic IsSerial Name     BaseType
-------- -------- ----     --------
True     True     String   System.Object

Here, $str is of type String.

Example 3: Array Type

Here is an example for a PowerShell array data type.

$arr = @(1, 2, 3)
$arrType = $arr.GetType()
Write-Output $arrType
IsPublic IsSerial Name     BaseType
-------- -------- ----     --------
True     True     Object[] System.Array

In this case, $arr is an array of objects.

Conclusion

I hope you now have an idea of the various data types in PowerShell. I have shown you the syntax and examples of each data type. Here is a summary:

  • Integers are used for whole number arithmetic.
  • Floats and Doubles handle fractional numbers with varying precision.
  • Decimals are crucial for high-precision arithmetic, especially in financial contexts.
  • Characters represent single Unicode characters.
  • Strings handle text data and support various operations.
  • Booleans are used for logical operations and control flow.
  • Dates manage date and time information.
  • Arrays store collections of items.
  • Hash Tables store key-value pairs for efficient lookups.
  • Custom Objects represent structured data with multiple properties.

You may also like:

Like most programming languages, PowerShell differentiates between integers and strings. While it’s easy to distinguish between strings and numbers, complex scripts may require combining the two. This raises the question of how to handle calculations when you need to work with a number that’s stored as a string.

What Happens If You Add Strings?

In situations like this, you have several options. Let’s consider a scenario where you have two string variables, $A and $B, and you need to add their values. If you simply type $A + $B, you will end up with a concatenation of those values. For example, if $A is 1 and $B is 3, $A + $B would result in 13, not 4. This happens because $A and $B are treated as strings, so adding them together just combines them as $A (1) + $B (3) is the same as $A $B, which results in 13.

PowerShell screenshot demonstrates that you can’t add strings together, even when the string variables contain numbers

You can’t add strings together, even when the string variables contain numbers.

For example, you might type:

PowerShell screenshot showing how to treat string data as numerical data

You can force PowerShell to treat string data as numerical data.

Evaluate the Expression

You can’t just convert “123+456″ into numerical format because it contains an operator. As such, there are a couple of options for handling a string like this.

One option is to parse the string and use character manipulation to extract the individual elements (e.g., number 123, the plus sign, and the number 456). While this approach is valid, it involves some tricky programming.

A more elegant solution is to treat the string as an expression to be evaluated. You can do this by using PowerShell’s Invoke-Expression command in conjunction with the string’s contents.

Such an operation might look like this:

PowerShell screenshot shows the use of Invoke-Expression cmdlet to evaluate a string

You can use the Invoke-Expression cmdlet to evaluate a string.

What If Invoke-Expression Fails?

The Invoke-Expression method I demonstrated is really straightforward. However, when dealing with a complex script, you may encounter situations where the Invoke-Expression command fails to produce results. In such cases, it often indicates that something might be wrong with your string. For example, you might not be dealing with true string data, or the string may contain invisible extra characters. To address this, I would like to introduce a technique.

The first step is to verify the variable’s type. The easiest way to do this is by appending .GetType() to the variable name. Check the resulting Name column to determine the variable’s type.

PowerShell screenshot shows a Name column indicating that a variable is a string variable

The Name column indicates that this is a string variable.

You can also check the variable’s length to ensure there are no hidden spaces at the beginning or end. Take, for instance, my $A variable, which contains the string “123+456”. This variable appears to have seven visible characters, with six of them being numbers and one being the operator (the plus sign). To check for the presence of extra, unseen characters, simply type the variable name and append .Length. You can see what this looks like in Figure 5.

PowerShell screenshot shows a variable being checked for the number of characters it contains

My variable contains seven characters.

If you encounter an unexpected result, it’s a signal to investigate why extra characters have found their way into your string. Once you eliminate these extra characters, you should be able to evaluate the expression correctly.

In case you can’t pinpoint the source of the extra characters, you can use the Trim operation to remove any leading or trailing spaces. For example, if $A contained extra characters, I could remove them by typing:

You can see what this looks like in Figure 6.

PowerShell screenshot showing the use of the Trim operation

I have used Trim to remove the extra spaces from my string.

Another reason why Invoke-Expression may fail is that, when used inside a script, it might not always produce visible output. A better approach is to map the Invoke-Expression to a variable and then tell PowerShell to display the variable.

:/>  Где находятся программы и компоненты в Windows 10

Here is an example of how to do this:

About the Author(s)

Brien Posey

Brien Posey is a bestselling technology author, a speaker, and a 20X Microsoft MVP. In addition to his ongoing work in IT, Posey has spent the last several years training as a commercial astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space.

How to convert $a to Int32?

Source: How To Convert PowerShell String Data to Integers

See also: PowerShell: Converting String Representations of Numbers to Integers – Stack Overflow


> $a = '1' -as [Int]
> $a.GetType().Name
Int32
> $a | gm

   TypeName: System.Int32

Name        MemberType Definition
----        ---------- ----------
CompareTo   Method     int CompareTo(System.Object value), int CompareTo(int value), int IComparable.CompareTo(System.Object obj), int IComparable[int].CompareTo(int other)
Equals      Method     bool Equals(System.Object obj), bool Equals(int obj), bool IEquatable[int].Equals(int other)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
GetTypeCode Method     System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode()
ToBoolean   Method     bool IConvertible.ToBoolean(System.IFormatProvider provider)
ToByte      Method     byte IConvertible.ToByte(System.IFormatProvider provider)
ToChar      Method     char IConvertible.ToChar(System.IFormatProvider provider)
ToDateTime  Method     datetime IConvertible.ToDateTime(System.IFormatProvider provider)
ToDecimal   Method     decimal IConvertible.ToDecimal(System.IFormatProvider provider)
ToDouble    Method     double IConvertible.ToDouble(System.IFormatProvider provider)
ToInt16     Method     short IConvertible.ToInt16(System.IFormatProvider provider)
ToInt32     Method     int IConvertible.ToInt32(System.IFormatProvider provider)
ToInt64     Method     long IConvertible.ToInt64(System.IFormatProvider provider)
ToSByte     Method     sbyte IConvertible.ToSByte(System.IFormatProvider provider)
ToSingle    Method     float IConvertible.ToSingle(System.IFormatProvider provider)
ToString    Method     string ToString(), string ToString(string format), string ToString(System.IFormatProvider provider), string ToString(string format, System.IFormatProvider provider), string IC…
ToType      Method     System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider)
ToUInt16    Method     ushort IConvertible.ToUInt16(System.IFormatProvider provider)
ToUInt32    Method     uint IConvertible.ToUInt32(System.IFormatProvider provider)
ToUInt64    Method     ulong IConvertible.ToUInt64(System.IFormatProvider provider)
TryFormat   Method     bool TryFormat(System.Span[char] destination, [ref] int charsWritten, System.ReadOnlySpan[char] format, System.IFormatProvider provider), bool ISpanFormattable.TryFormat(Syste…

>

PowerShell belongs to a dynamic, not strongly typed-language class, meaning you are not required to declare the data type of variables. Simply put, PowerShell is smart enough to determine the data type on the fly.

Again, it is not required to specify the object type, but it doesn’t mean you can’t. Some scenarios may still strongly type the object, especially when converting to another type, such as our topic in this post.

PowerShell is So Smart. It Just Works!

The first question is, how do you know the object’s data type? Let’s find out.

For example, let’s create two sample variables and assign the same value.

# Create variables and assign values 
$a = 1 
$b = '1'

# Display the variable values
$a
$b

powershell convert string to int

As you can see, both variables return the exact value of 1. If so, we can use these values in a mathematical operation. Let’s see by adding these two values.

$a + $b

powershell string to int

There’s no error. An addition was performed on the two values and returned the correct result. Does that mean these two values are of the same data type? The answer is no, and here’s how you can find out.

$a.GetType() 
$b.GetType()

As you can see, PowerShell automatically assigned $a as an Int32 (32-bit integer) and $b as a String. So, they are different, after all.

convert string to int powershell

This demonstration is just one example of how smart PowerShell is when handling objects and data types. It can evaluate expressions and make decisions on how to handle them. In this case, PowerShell understands that you want to add 1 and ‘1’ together.

But just because PowerShell could doesn’t mean you should rely on this automatic determining of types and expressions. Significantly when scripting and working on multiple data types, it would benefit you to cast values as the intended types to avoid debugging headaches.

Hint. Other popular data types in PowerShell:

How to Convert String to Integer in PowerShell?

If you try to explicitly assign a string value to a numeric variable or try to perform other numeric operation, you get an error:

[int]$number = 'Ten'

MetadataError: Cannot convert value “Ten” to type “System.Int32”. Error: “The input string ‘Ten’ was not in a correct format.”

powershell convert to int

There are several ways to convert the string to an integer, giving the same result.

Let’s say you have a variable containing a string (type System.String):

$stringN = "777" 
$stringN.GetType().FullName

The screenshot below confirms that “777” is not a number but a word.

powershell convert string to int64

You can convert the string to integer using these techniques.

  • Strongly type the variable:
    [int]$stringN

    powershell toint

  • Using the [int]::Parse() method:
    [int]::Parse($stringN)

    powershell string to int64

  • Using the <value> -as [datatype] statement:
    $stringN -as [int]

    powershell to int

  • Calling the String.ToInt32() method:
    $stringN.ToInt32($null)

    powershell string to integer

  • Using the [convert]::ToInt32() method:
    [convert]::ToInt32($stringN)

    powershell toint32
    Note. Learn how to use Group Policy to manage, add, modify, import, and delete registry keys.

  • Tip: The [convert] class allows you to convert a value not only to Int32, but also to other integer data types:
    • [convert]::ToInt16 — Signed 16-bit integer (short)
    • [convert]::Int64 — Signed 64-bit integer (long)
    • [convert]::UInt32 — Unsigned 32-bit integer (uint)
    • [convert]::UInt64 — Unsigned 64-bit integer (ulong)

Check for Integer Input in PowerShell Scripts

Function IsInteger { 
param( 
[string]$vInteger 
) 
Try { 
$null = [convert]::ToInt32($vInteger) 
return $True 
} 
Catch { 
return $False 
} 
}

You can check the correctness of the function on the test data:

IsInteger "five" 
IsInteger "70.1" 
IsInteger "100" 
IsInteger 100

powershell convert string to integer

Converting Formatted String to Integer

Sometimes the supposed numeric value is shown as a formatted string, such as those with “,” for thousands notation.

$value1 = "120,830,200" 
$value2 = "120,830,200 (bytes)"

You understand these values, but none of the string-to-integer conversion methods we learned will work because these are not purely numbers.

powershell parse int

In this case, you must employ string manipulation to clean up the values and retain the numbers only.

Specific to the above examples, one way is to use the String.Replace() method.

$value1.Replace(',',$null) 
$value2.Replace(',',$null).Replace(' (bytes)',$null)

convert string to number powershell

Since the values have been cleaned up, you can now convert them to integers using any methods we discussed.

[int]($value1.Replace(',',$null)) 
$value2.Replace(',',$null).Replace(' (bytes)',$null) -as [int]

powershell toint16

In conclusion, PowerShell’s dynamic and adaptable nature makes it a powerful tool for handling various data types and operations. While PowerShell can often determine the data type and perform operations seamlessly, it’s essential to be aware of potential type mismatches that can lead to unexpected outcomes.

The ability to automatically assign data types, as demonstrated by the example of adding an integer and a string, showcases PowerShell’s intelligent handling of expressions.

However, this automation doesn’t negate the importance of understanding and explicitly handling data types, especially when working with diverse data sets or in scripting scenarios. Explicitly casting values to their intended types, as we explored in this post, helps avoid potential debugging challenges.

Cyril Kardashevsky

Оставьте комментарий