Как преобразовать строку в int 32

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…

>

How to modify the font size in a .lnk file using PowerShell

The font size, and other properties, in a .lnk file can be edited by searching through its internal structures for the structure that has the desired property as a member. In the case of changing the font size, the desired structure is CONSOLE_PROPS, and the desired member is “The two most significant bytes” of FontSize, which contain the font height.

Load the Shortcut File: Start by loading the .lnk file into a byte array. This allows us to edit the file in memory.

$lnkPath = "$PSScriptRoot\CustomPowerShell.lnk"
$lnkContent = [IO.File]::ReadAllBytes($lnkPath)

Identify Structures: Determine which structures are present, and will need to be navigated, in the file by reading the link flags. Also, move $pointer past the first, and only mandatory structure, ShellLinkHeader.

$pointer = [BitConverter]::ToUInt32($lnkContent, 0x0)
$linkFlags = [BitConverter]::ToUInt32($lnkContent, 0x0014)

Navigate Identified Structures: Increment $pointer, moving past each existing structure, until the arriving at the extra data section of the .lnk file.

if ($linkFlags -band 0x00000001) { $pointer += 2 + [BitConverter]::ToUInt16($lnkContent, $pointer) }     #  HasLinkTargetIDList
if ($linkFlags -band 0x00000002) { $pointer += [BitConverter]::ToUInt32($lnkContent, $pointer) }         #  HasLinkInfo
if ($linkFlags -band 0x00000004) { $pointer += 2 + 2 * [BitConverter]::ToUInt16($lnkContent, $pointer) } #  HasName
if ($linkFlags -band 0x00000008) { $pointer += 2 + 2 * [BitConverter]::ToUInt16($lnkContent, $pointer) } #  HasRelativePath
if ($linkFlags -band 0x00000010) { $pointer += 2 + 2 * [BitConverter]::ToUInt16($lnkContent, $pointer) } #  HasWorkingDir
if ($linkFlags -band 0x00000020) { $pointer += 2 + 2 * [BitConverter]::ToUInt16($lnkContent, $pointer) } #  HasArguments
if ($linkFlags -band 0x00000040) { $pointer += 2 + 2 * [BitConverter]::ToUInt16($lnkContent, $pointer) } #  HasIconLocation
if ($linkFlags -band 0x00000200) { $pointer += [BitConverter]::ToUInt32($lnkContent, $pointer) }         #  HasExpString
if ($linkFlags -band 0x00001000) { $pointer += [BitConverter]::ToUInt32($lnkContent, $pointer) }         #  HasDarwinID
if ($linkFlags -band 0x00004000) { $pointer += [BitConverter]::ToUInt32($lnkContent, $pointer) }         #  HasExpIcon
while ( ( $blockSize = [BitConverter]::ToUInt32($lnkContent, $pointer) ) -ge 0x00000004) {
   $blockSignature = [BitConverter]::ToUInt32($lnkContent, ($pointer + 4))
   if ( $blockSignature -eq [uint32]'0xA0000002') {   #  CONSOLE_PROPS / ConsoleDataBlock
      $posFontHeight = $pointer + 34
      $NewFontHeight = 24
      ([BitConverter]::GetBytes([UInt16]$NewFontHeight)).CopyTo($lnkContent, $posFontHeight)
   }
   $pointer += $blockSize
}

Write Changes to File: After modifying the font height, save the changes back to the file. Optionally, modify this part to save to a new file instead.

[IO.File]::WriteAllBytes($lnkPath, $lnkContent)

The above code edits only the font height. You can similarly modify other properties in any structure, not just CONSOLE_PROPS, by navigating to the correct structure, and then navigating to the desired property in that structure.

Recently, I got a requirement in PowerShell to convert a string to int. I tried different methods to do so. In this tutorial, I will explain how to convert string to integer in PowerShell using various methods. Using different examples, I will also show you how to convert string to number with decimal in PowerShell.

A PowerShell string is a sequence of characters, while an integer is a whole number without a fractional component. Converting a string to an integer in PowerShell means interpreting the characters in the string as a numerical value.

Here, let us check different methods to convert a string to an integer in PowerShell using various methods.

Method 1: Type Casting

Type casting is the simplest method to convert a string to an integer. It involves prefixing the variable with the desired data type in square brackets. Here’s an example:

[string]$stringNumber = "42"
[int]$integerNumber = [int]$stringNumber
Write-Host $integerNumber

Once you execute the PowerShell script, you can see the output in the screenshot below.

Convert String to Integer in PowerShell

Method 2: Using the -as Operator

Another way to perform the conversion is by using the -as operator, which attempts to convert the value on its left to the type specified on its right:

$stringNumber = "42"
$integerNumber = $stringNumber -as [int]
Write-Host $integerNumber

This will also result in 42 being output as an integer. The -as operator is safe to use because if the conversion fails, it will return $null instead of throwing an exception.

:/>  Быстрый доступ к папке Temp

Method 3: Parse and TryParse Methods

$stringNumber = "42"
$integerNumber = [int]::Parse($stringNumber)
Write-Host $integerNumber

If $stringNumber is not a valid integer, this method will throw an exception. To avoid exceptions and handle conversion errors more gracefully, you can use the TryParse method:

$stringNumber = "42"
$integerNumber = 0
[bool]$result = [int]::TryParse($stringNumber, [ref]$integerNumber)
if ($result) {
    Write-Host $integerNumber
} else {
    Write-Host "Conversion failed"
}

The TryParse method returns a boolean indicating whether the conversion succeeded and outputs the converted integer through its second parameter.

You can see the output in the screenshot below:

How to Convert String to Integer in PowerShell

Method 4: Convert Class

The Convert class in .NET provides a ToInt32 method that can convert various types to a 32-bit integer. Here’s how you can use it in PowerShell:

$stringNumber = "42"
$integerNumber = [convert]::ToInt32($stringNumber)
Write-Host $integerNumber

This method is similar to Parse, but it can handle null and other types more gracefully.

Handling Non-Numeric Strings

It’s essential to consider what happens when a string cannot be converted to an integer. For instance, if you try to convert a string with alphabetical characters, all the methods discussed will fail or return $null. It’s good practice to validate the string before attempting conversion or to use TryParse to handle potential errors without throwing exceptions.

Advanced Conversion Scenarios

Sometimes, strings represent numbers in different bases, such as hexadecimal. PowerShell can handle these cases as well:

$hexString = "2A"
$integerNumber = [convert]::ToInt32($hexString, 16)
Write-Host $integerNumber

This script will output 42, which is the decimal equivalent of the hexadecimal number 2A.

Maximizing Storage Efficiency: Using PowerShell for Folder Size Analysis


  • by Team Ninjareviewed by Stan Hunter, Technical Marketing Engineer

Key Takeaways

  • The PowerShell script efficiently calculates and reports folder sizes in Windows environments.
  • It is adaptable, allowing users to specify a path, folder depth, and minimum size threshold.
  • The script supports a range of size units (KB, MB, GB, etc.) for defining minimum folder size.
  • Ideal for IT professionals and MSPs needing a quick overview of disk space usage.
  • Includes features for handling permission issues and providing more accurate results.
  • Employs a user-friendly output, displaying folder paths and their corresponding sizes.
  • Useful in scenarios like server maintenance, storage optimization, and data cleanup.
  • Offers a more script-based, customizable alternative to traditional disk analysis tools.

Efficient data management is a cornerstone of IT operations, where insights into data distribution and storage play a crucial role. PowerShell, with its versatile scripting capabilities, stands as a potent tool for IT professionals. A script that can list and measure folder sizes is not just a convenience—it’s a necessity for maintaining optimal performance and storage management in various IT environments.

Background

The provided PowerShell script targets an essential need in the IT sector: understanding and managing folder sizes within a system. For IT professionals and Managed Service Providers (MSPs), this is more than a matter of simple housekeeping. In an era where data grows exponentially, keeping tabs on which folders are consuming the most space can lead to more informed decisions about resource allocation, system optimization, and data management policies. This script specifically caters to these needs by enabling a detailed analysis of folder sizes.

The Script:

#Requires -Version 5.1

<#
.SYNOPSIS
    Get a tree list of folder sizes for a given path with folders that meet a minimum folder size.
.DESCRIPTION
    Get a tree list of folder sizes for a given path with folders that meet a minimum folder size.
    Be default this looks at C:, with a folder depth of 3, and filters out any folder under 500 MB.
.EXAMPLE
    (No Parameters)
    Gets folder sizes under C: for a depth of 3 folders and displays folder larger than 500 MB.
.EXAMPLE
    -Path C:
    -Path C: -MinSize 1GB
    -Path C:Users -Depth 4

PARAMETER: -Path C:
    Gets folder sizes under C:.

PARAMETER: -Path C: -MinSize 1GB
    Gets folder sizes under C:, but only returns folder larger than 1 GB.
    Don't use quotes around 1GB as PowerShell won't be able to expand it to 1073741824.

PARAMETER: -Path C:Users -Depth 4
    Gets folder sizes under C:Users with a depth of 4.

.OUTPUTS
    String[] or PSCustomObject[]
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes: Renamed script and added Script Variable support
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [String]$Path = "C:",
    [int]$Depth = 3,
    $MinSize = 500MB
)

begin {
    function Get-Size {
        param ([string]$String)
        switch -wildcard ($String) {
            '*PB' { [int64]$($String -replace '[^d+]+') * 1PB; break }
            '*TB' { [int64]$($String -replace '[^d+]+') * 1TB; break }
            '*GB' { [int64]$($String -replace '[^d+]+') * 1GB; break }
            '*MB' { [int64]$($String -replace '[^d+]+') * 1MB; break }
            '*KB' { [int64]$($String -replace '[^d+]+') * 1KB; break }
            '*B' { [int64]$($String -replace '[^d+]+') * 1; break }
            '*Bytes' { [int64]$($String -replace '[^d+]+') * 1; break }
            Default { [int64]$($String -replace '[^d+]+') * 1 }
        }
    }

    $Path = if ($env:rootPath) { Get-Item -Path $env:rootPath }else { Get-Item -Path $Path }
    if ($env:Depth) { $Depth = [System.Convert]::ToInt32($env:Depth) }
    $MinSize = if ($env:MinSize) { Get-Size $env:MinSize }else { Get-Size $MinSize }

    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    function Test-IsSystem {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        return $id.Name -like "NT AUTHORITY*" -or $id.IsSystem
    }

    if (!(Test-IsElevated) -and !(Test-IsSystem)) {
        Write-Host "[Warning] Not running as SYSTEM account, results might be slightly inaccurate."
    }
    function Get-FriendlySize {
        param($Bytes)
        # Converts Bytes to the highest matching unit
        $Sizes = 'Bytes,KB,MB,GB,TB,PB,EB,ZB' -split ','
        for ($i = 0; ($Bytes -ge 1kb) -and ($i -lt $Sizes.Count); $i++) { $Bytes /= 1kb }
        $N = 2
        if ($i -eq 0) { $N = 0 }
        if ($Bytes) { "{0:N$($N)} {1}" -f $Bytes, $Sizes[$i] }else { "0 B" }
    }
    function Get-SizeInfo {
        param(
            [parameter(mandatory = $true, position = 0)][string]$TargetFolder,
            #defines the depth to which individual folder data is provided
            [parameter(mandatory = $true, position = 1)][int]$DepthLimit
        )
        $obj = New-Object PSObject -Property @{Name = $targetFolder; Size = 0; Subs = @() }
        # Are we at the depth limit? Then just do a recursive Get-ChildItem
        if ($DepthLimit -eq 1) {
            $obj.Size = (Get-ChildItem $targetFolder -Recurse -Force -File -ErrorAction SilentlyContinue | Measure-Object -Sum -Property Length).Sum
            return $obj
        }
        # We are not at the depth limit, keep recursing
        $obj.Subs = foreach ($S in Get-ChildItem $targetFolder -Force -ErrorAction SilentlyContinue) {
            if ($S.PSIsContainer) {
                $tmp = Get-SizeInfo $S.FullName ($DepthLimit - 1)
                $obj.Size += $tmp.Size
                Write-Output $tmp
            }
            else {
                $obj.Size += $S.length
            }
        }
        return $obj
    }
    function Write-Results {
        param(
            [parameter(mandatory = $true, position = 0)]$Data,
            [parameter(mandatory = $true, position = 1)][int]$IndentDepth,
            [parameter(mandatory = $true, position = 2)][int]$MinSize
        )
    
        [PSCustomObject]@{
            Path     = "$((' ' * ($IndentDepth + 2)) + $Data.Name)"
            Size     = Get-FriendlySize -Bytes $Data.Size
            IsLarger = $Data.Size -ge $MinSize
        }

        foreach ($S in $Data.Subs) {
            Write-Results $S ($IndentDepth + 1) $MinSize
        }
    }
    function Get-SubFolderSize {
        [CmdletBinding()]
        param(
            [parameter(mandatory = $true, position = 0)]
            [string]$targetFolder,
    
            [int]$DepthLimit = 3,
            [int]$MinSize = 500MB
        )
        if (-not (Test-Path $targetFolder)) {
            Write-Error "The target [$targetFolder] does not exist"
            exit
        }
        $Data = Get-SizeInfo $targetFolder $DepthLimit
    
        #returning $data will provide a useful PS object rather than plain text
        # return $Data
    
        #generate a human friendly listing
        Write-Results $Data 0 $MinSize
    }
}
process {
    Get-SubFolderSize -TargetFolder $Path -DepthLimit $Depth -MinSize $MinSize | Where-Object { $_.IsLarger } | Select-Object -Property Path, Size
}
end {
    
    
    
}

Access 300+ scripts in the NinjaOne Dojo

Detailed Breakdown

  • Parameter Initialization: It begins by defining parameters like Path, Depth, and MinSize. These parameters allow users to specify the search directory, the depth of the directory tree to analyze, and the minimum folder size to report.
  • Size Conversion Function (Get-Size): This function converts different size units (KB, MB, GB, etc.) into bytes, ensuring uniformity in size measurement.
  • Environment Variable Checks: The script checks and adapts to environmental variables, if set, allowing for dynamic path, depth, and size configurations.
  • Elevation and System Account Checks: It examines whether the script runs under elevated privileges or a system account, crucial for accessing certain directories and ensuring accuracy.
  • Folder Size Calculation (Get-SizeInfo): This recursive function traverses the folder hierarchy, accumulating the size of files and folders up to the specified depth.
  • Result Formatting (Write-Results): The gathered data is then formatted into a readable structure, showing the path and the size of folders that exceed the specified minimum size.
  • Execution (Get-SubFolderSize): The core function that ties all components together, executing the size calculation and result formatting.
  • Output: Finally, the script outputs the data, focusing on folders larger than the minimum size set by the user.

Potential Use Cases

Comparisons

FAQs

  • Q: Can this script analyze network drives?
    A: Yes, provided the user has the necessary permissions and the drive is accessible.
  • Q: Does the script require administrative privileges?
    A: While not always necessary, running the script as an administrator ensures comprehensive access to all folders.
  • Q: How can I modify the minimum folder size?
    A: Change the MinSize parameter to your desired threshold.

Beyond storage management, the script’s output can have implications for IT security. Large, unexpected files could be a sign of security breaches, like data dumps. Regular monitoring using such scripts can be part of a proactive security strategy.

Recommendations

  • Regularly run the script for proactive storage management.
  • Combine the script’s output with other system monitoring tools for comprehensive insights.
  • Be cautious about system load when running this script on servers with extensive directories.

Final Thoughts

In the context of data-driven solutions like NinjaOne, PowerShell scripts like these complement broader IT management strategies. By automating and simplifying complex tasks, such as analyzing folder sizes, IT professionals can focus on more strategic initiatives, ensuring systems are not just operational, but also optimized and secure. With NinjaOne’s integration capabilities, scripts like this can be part of a more extensive toolkit for efficient IT management.

Convert string to int error handling

Error handling is an important aspect when converting strings to integers in PowerShell, especially when the string may not represent a valid integer. PowerShell provides several methods to handle errors that may occur during the conversion process.

Using TryParse for Error Handling

Here’s an example:

$stringNumber = "notanumber"
$integerNumber = 0
$result = [int]::TryParse($stringNumber, [ref]$integerNumber)

if ($result) {
    "Conversion successful: $integerNumber"
} else {
    "Conversion failed."
}

If $stringNumber is not a valid integer, $result will be $false, and $integerNumber will remain 0.

You can see in the screenshot below that I executed the script using VS code.

PowerShell convert string to int error handling

Using Try/Catch Blocks

$stringNumber = "notanumber"

try {
    $integerNumber = [int]::Parse($stringNumber)
    "Conversion successful: $integerNumber"
} catch [System.FormatException] {
    "Conversion failed: Input string was not in a correct format."
} catch {
    "Conversion failed with an unexpected error: $_"
}

In this example, if the string is not a valid integer, a System.FormatException will be caught and handled.

Using Conditional Logic with -as Operator

The -as operator in PowerShell can be used for error handling because it returns $null if the conversion is not possible, which can be checked using conditional logic.

$stringNumber = "notanumber"
$integerNumber = $stringNumber -as [int]

if ($null -eq $integerNumber) {
    "Conversion failed."
} else {
    "Conversion successful: $integerNumber"
}

This method is less explicit than TryParse but can be useful for simple conversions where the presence of a non-integer value is not critical.

Convert string to number with decimal in PowerShell

1. Using Type Casting

To convert a string to a double in PowerShell, you can cast the string directly:

[string]$stringNumber = "123.45"
[double]$doubleNumber = [double]$stringNumber
Write-Host $doubleNumber

For a decimal, the process is similar:

[string]$stringNumber = "123.45"
[decimal]$decimalNumber = [decimal]$stringNumber
Write-Host $decimalNumber

2. Using the Convert Class

The Convert class provides methods to convert strings to numbers with decimals in PowerShell:

[string]$stringNumber = "123.45"
[double]$doubleNumber = [convert]::ToDouble($stringNumber)
Write-Host $doubleNumber

For converting to a decimal:

[string]$stringNumber = "123.45"
[decimal]$decimalNumber = [convert]::ToDecimal($stringNumber)
Write-Host $decimalNumber

3. Error Handling with TryParse

For error handling, you can use the TryParse method of the double or decimal type to convert the string and catch any conversion errors safely in PowerShell:

[string]$stringNumber = "notanumber"
[double]$doubleNumber = 0
$result = [double]::TryParse($stringNumber, [ref]$doubleNumber)

if ($result) {
    "Conversion successful: $doubleNumber"
} else {
    "Conversion failed."
}
[string]$stringNumber = "notanumber"
[decimal]$decimalNumber = 0
$result = [decimal]::TryParse($stringNumber, [ref]$decimalNumber)

if ($result) {
    "Conversion successful: $decimalNumber"
} else {
    "Conversion failed."
}

4. Using -as Operator

The -as operator can also be used for converting strings to numbers with decimals in PowerShell, with the added benefit of not throwing an error on failure:

[string]$stringNumber = "123.45"
[double]$doubleNumber = $stringNumber -as [double]

if ($doubleNumber -eq $null) {
    "Conversion failed."
} else {
    "Conversion successful: $doubleNumber"
}

You can see the output in the screenshot below:

Convert string to number with decimal in PowerShell

Conclusion

In this PowerShell tutorial, I have explained how to convert a string to an integer in PowerShell using various methods.

  • Type Casting
  • Using the -as Operator
  • Parse and TryParse Methods
  • Convert Class

Also, I have explained:

  • PowerShell convert string to int error handling
  • Convert string to number with decimal in PowerShell

You may also like:

Bijay Kumar

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