Оспрос тм

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

Conclusion

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.

:/>  Работа в windows на клавиатуре. Полезные сочетания клавиш . Длиннопост.⁠⁠

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

Your JSON string – with properly quoted property names – does work, but a long-standing bug prevented it from getting passed properly to curl.exe:

  • As detailed in this answer, Windows PowerShell and PowerShell (Core) up to v7.2.x require " characters embedded in PowerShell strings to be explicitly escaped as \" when passed to external programs such as curl.exe

  • Passing a programmatically escaped value, ($json -replace '(\\*)"', '$1$1\"'), in lieu of just $json to curl.exe solved the problem.

    • For instance, this programmatic escaping turns verbatim { "foo": "3\" of snow" } into verbatim { \"foo\": \"3\\\" of snow\" }, which PowerShell then encloses in "..." on the process command line.[1]

Given that your web service seemingly accepts this simplified format, using it would indeed avoid the "-related bug (assuming that there aren’t any property values with embedded ").

While ConvertFrom-Json can read this simplified format too (in both PowerShell editions), ConvertTo-Json cannot create it (in neither edition).

'{"ISOYear":[{"ISOYear":2023}],"ISOWeek":[{"ISOWeek":23}],"SkillCategory":"Warehouse","Building":"ABC"}' | ConvertFrom-Json | ConvertTo-SimplifiedJson
{ISOYear:[{ISOYear:2023}],ISOWeek:[{ISOWeek:23}],SkillCategory:'Warehouse',Building:'ABC'}

ConvertTo-SimplifiedJson source code:
# Creates a simplified JSON representation for the given object (graph)
# using unquoted property names, where possible, and single-quoting for string values.
# Note:
# * The resulting respresentation is compressed (no whitespace for readability).
# * Property values of types that cannot be represented in JSON are represented
# as strings:
# * [datetime] and [datetimeoffset] instances are stringified as ISO 8601 timestamps,
# using .ToString('o')
# * All other such types are represented by their .ToString() values.
function ConvertTo-SimplifiedJson { param([Parameter(ValueFromPipeline)] [object] $InputObject) begin { function test-ListLike { param($o) $o -is [System.Collections.IEnumerable] -and $o -isnot [string] -and $o -isnot [System.Collections.IDictionary] } } process { $properties = if ($InputObject -is [System.Collections.IDictionary]) { $InputObject.GetEnumerator() } else { $InputObject.psobject.Properties } if (test-ListLike $InputObject) { # array as single input object -> recurse '[' + $(foreach ($o in $InputObject) { ConvertTo-SimplifiedJson $o }) + ']' } elseif ($InputObject.GetType() -in [datetime], [datetimeoffset]) { "'{0}'" -f $InputObject.ToString('o') # Use an ISO 8601 time string } elseif ($InputObject -is [bool]) { "$($InputObject)".ToLower() # JSON requires case-exact 'true' or 'false' } elseif ($InputObject.GetType() -in [byte], [sbyte], [int16], [uint16], [int32], [uint32], [int64], [uint64], [bigint], [decimal], [float], [double] ) { # A number type. [string] $InputObject # Use culture-invariant stringification, to be embedded unquoted in the JSON. } elseif ($InputObject.GetType() -in [char], [string] -or $properties.Count -eq 0) { # A char., a string, or an unsupported property-less object. "'{0}'" -f ($InputObject -replace "'", "\'") } else { # A (nested) object that doesn't map onto a JSON primitive. # Recursively process its properties. $sep = '{' -join $( foreach ($p in $properties) { $name = if ($p.Name -notmatch '\W') { $p.Name } else { "'{0}'" -f ($p.Name -replace "'", "\'") } $value = ConvertTo-SimplifiedJson $p.Value '{0}{1}:{2}' -f $sep, $name, $value $sep = ',' } ) + '}' } }
}

PowerShell as a 電卓

image

(上図はPowerShell Coreで実行していますが、Windows PowerShellでも同様です)

image

PowerShellを電卓として使う際のTips集

1. 基本的な演算子

演算子用例内容
+1 + 2加算、プラス
1 – 2減算、マイナス
*1 * 2乗算
/10 / 2除算
%10 % 3余剰

2. 暗黙の型

PowerShellで扱う数値は内部で型を持っており、型を明示しない場合は整数はint型 (System.Int32)またはlong型(System.Int64)(intの範囲を超える場合)、小数はdouble型 (System.Double)となります。

# 整数は int型(int32)C:\> 123 TypeName: SystemInt32
・・・ 省略 ・・・# intの範囲を超える整数は long型(int64)C:\> 2147483648   TypeName: SystemInt64
・・・ 省略 ・・・# 小数は double型C:\> 12345 TypeName: SystemDouble
・・・ 省略 ・・・
# 接尾語 d は decimal型C:\> 123d TypeName: SystemDecimal
・・・ 省略 ・・・

3. 丸め、0除算

C:\> 125
12
C:\> ::Round125 ::AwayFromZero
13
C:\> 123/0
Attempted to divide by zero
At line:1 char:1 123/0 ~~~~~ CategoryInfo : NotSpecified: : RuntimeException FullyQualifiedErrorId : RuntimeException
C:\> 12345/0
∞
C:\> 12345/0
∞

4. 数値計算クラス

C:\> ::Pow210
1024

5. 基数変換

C:\> 31ToString
1f
C:\> ::ToString318
37

6. 多倍長整数、複素数など

.NET Framework 4.0を基盤とするPowerShell 3.0以降でのみ可能なTipsです。
.NET Framework 4.0からはSystem.Numerics名前空間多倍長整数型(BigIngeter)複素数型(Complex)が追加されており、PowerShellからも利用することが可能です。

C:\> ::Pow::MaxValue 3
784637716923335095224261902710254454442933591094742482943
C:\> = SystemNumericsComplex 1 2
C:\> = SystemNumericsComplex 3 4
C:\>
Real Imaginary Magnitude Phase 4 6 721110255092798 0982793723247329

7. Excel関数

Windows PowerShellとPowerShell CoreでVB.NET独自機能対する実装が異なるため、この方法を使えるのはWindows PowerShellだけとなります。

# 以下は Windows PowerShellでのみ可能 (PowerShell Coreでは不可)# SLN(取得価額, 残存価額, 耐用年数)で指定C:\> AssemblyName
C:\> ::SLN150000 15000 5
27000

8. PoweShell関数

L4V4NY4 AGR3

Task 1 Introduction

  • What is Osquery, and what problem it solves?
  • Osquery in Interactive Mode
  • How to use the interactive mode of Osquery to interact with the operating system
  • How to join two tables to get a single answer
:/>  Исправление отсутствия Origin MSVCP140.dll [4 метода]

Note: It is highly beneficial if you’re already familiar with SQL queries. If not, check out this SQL Tutorial.

Answer the questions below

Move on to the next task.

No Needed Answer

Task 2 Connect with the Lab

Click on the powershell terminal pinned at the taskbar and enter osqueryi to enter the interactive mode of osquery.

Machine IP: ip

Note that it will take 3–5 minutes for the VM to boot up completely.

Answer the questions below

Connect with the Lab.

No Needed Answer

Task 3 Osquery: Interactive Mode

One of the ways to interact with Osquery is by using the interactive mode. Open the terminal and run run osqueryi. To understand the tool, run the .help command in the interactive terminal, as shown below:

— osquery interactive mode —

Note: As per the documentation, meta-commands are prefixed with a ..

List the tables

To list all the available tables that can be queried, use the .tables meta-command.

For example, if you wish to check what tables are associated with processes, you can use .tables process.

— osquery interactive mode —

— osquery interactive mode —

Understanding the table Schema

Table names are not enough to know what information it contains without actually querying it. Knowledge of columns and types (known as a schema ) for each table is also helpful.

— osquery interactive mode —

SQL QUERY SYNTAX: select column1, column2, column3 from table;

— osquery interactive mode —

Osquery comes with multiple display modes to select from. Use the .help option to list the available modes or choose 1 of them as shown below:

— osquery interactive mode —

The schema API online documentation can be used to view a complete list of tables, columns, types, and column descriptions.

Answer the questions below

How many tables are returned when we query “table process” in the interactive mode of Osquery?

Looking at the schema of the processes table, which column displays the process id for the particular process?

Examine the .help command, how many output display modes are available for the .mode command?

Task 4 Schema Documentation

For this task, go to the schema documentation of Osquery version 5.5.1, the latest version. The schema documentation looks like the image shown below:

Let’s break down the important information we could find in this schema documentation:

  1. A dropdown lists various versions of Osquery. Choose the version of Osquery you wish to see schema tables for.
  2. The number of tables within the selected version of Osquery. (In the above image, 106 tables are available).
  3. The list of tables is listed in alphabetical order for the selected version of Osquery. This is the same result we get when we use the .table command in the interactive mode.
  4. The name of the table and a brief description.
  5. A detailed chart showing each table’s column, type, and description.
  6. Information to which Operating System the table applies. (In the above image, the account_policy_data table is available only for macOS)
  7. A dropdown menu to select the Operating System of choice. We can choose multiple Operating Systems, which will display the tables available for those Operating systems.

You have enough information to navigate this resource to retrieve any necessary information confidently.

Answer the questions below

In Osquery version 5.5.1, how many common tables are returned, when we select both Linux and Window Operating system?

# read the documentation in the provided link.

In Osquery version 5.5.1, how many tables for MAC OS are available?

# read the documentation in the provided link

In the Windows Operating system, which table is used to display the installed programs?

# read the documentation in the provided link

In Windows Operating system, which column contains the registry value within the registry table?

# read the documentation in the provided link

Task 5 Creating SQL queries

The SQL language implemented in Osquery is not an entire SQL language that you might be accustomed to, but rather it’s a superset of SQLite.

:/>  Почему дисковод не видит данные? Причины и их устранение

Realistically all your queries will start with a SELECT statement. This makes sense because, with Osquery, you are only querying information on an endpoint. You won’t be updating or deleting any information/data on the endpoint.

The exception to the rule: Using other SQL statements, such as UPDATE and DELETE, is possible, but only if you’re creating run-time tables (views) or using an extension if the extension supports them.

Your queries will also include a FROM clause and end with a semicolon.

Exploring Installed Programs

If you wish to retrieve all the information about the installed programs on the endpoint, first understand the table schema either using the .schema programs command in the interactive mode or use the documentation here.

Query: SELECT * FROM programs LIMIT 1;

— osquery interactive mode —

Note: Your results will be different if you run this query in the attached VM or your local machine (if Osquery is installed). Here line mode is used to display the result.

The number of columns returned might be more than what you need. You can select specific columns rather than retrieve every column in the table.

Query: SELECT name, version, install_location, install_date from programs limit 1;

— osquery interactive mode —

The above query will list the name, version, install location, and installed date of the programs on the endpoint. This will still return many results, depending on how busy the endpoint is.

To see how many programs or entries in any table are returned, we can use the count() function, as shown below:

Query: SELECT count(*) from programs;

— osquery interactive mode —

— osquery interactive mode —

The equal sign is not the only filtering option in a WHERE clause. Below are filtering operators that can be used in a WHERE clause:

  • = [equal]
  • <> [not equal]
  • >, >= [greater than, greater than, or equal to]
  • <, <= [less than or less than or equal to]
  • BETWEEN [between a range]
  • LIKE [pattern wildcard searches]
  • % [wildcard, multiple characters]
  • _ [wildcard, one character]

Matching Wildcard Rules

Below is a screenshot from the Osquery documentation showing examples of using wildcards when used in folder structures:

  • %: Match all files and folders for one level.
  • %%: Match all files and folders recursively.
  • %abc: Match all within-level ending in “abc”.
  • abc%: Match all within-level starting with “abc”.
  • /Users/%/Library: Monitor for changes to every user’s Library folder, but not the contents within.
  • /Users/%/Library/: Monitor for changes to files within each Library folder, but not the contents of their subdirectories.
  • /Users/%/Library/%: Same, changes to files within each Library folder.
  • /Users/%/Library/%%: Monitor changes recursively within each Library.
  • /bin/%sh: Monitor the bin directory for changes ending in sh.

Some tables require a WHERE clause, such as the file table, to return a value. If the required WHERE clause is not included in the query, then you will get an error.

— osquery interactive mode —

Joining Tables using JOIN Function

— osquery interactive mode —

Query1: select uid, pid, name, path from processes;

— osquery interactive mode —

Answer the questions below

Using Osquery, how many programs are installed on this host?

Query: select * from ie_extensions;

Query: select name,install_location from programs where name LIKE ‘%wireshark%’;

Wireshark 3.6.8 64-bit

Task 6 Challenge and Conclusion

Answer the questions below

Which table stores the evidence of process execution in Windows OS?

Create a search query to identify the VPN installed on this host. What is name of the software?

How many services are running on this host?

A table autoexec contains the list of executables that are automatically executed on the target machine. There seems to be a batch file that runs automatically. What is the name of that batch file (with the extension .bat)?

What is the full path of the batch file found in the above question? (Last in the List)

“ SECURING- DIGITAL ASSEST OF LIFE”