Определить тип аргумента PowerShell

Contents
Введение
Пример
Типы данных
В других языках
Похожие статьи

Введение

Получить тип переменной в PowerShell можно с помощью метода GetType()

Пример

$myVar = 42 $myVar.GetType()

IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType

Типы данных

Пройдемся по разным типам данных

$var_int = 0 $var_long = 2147483648 $var_float = 1.0 $var_str = "testsetup.ru" $var_bool = $true $var_arr = 1, 2, 3, 4 $var_hash = @{ url = "heihei.ru" topic = "travel" } Write-Output $var_int.GetType() Write-Output $var_long.GetType() Write-Output $var_float.GetType() Write-Output $var_str.GetType() Write-Output $var_bool.GetType() Write-Output $var_arr.GetType() Write-Output $var_hash.GetType()

IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType True True Int64 System.ValueType True True Double System.ValueType True True String System.Object True True Boolean System.ValueType True True Object[] System.Array True True Hashtable System.Object

Разберем более экзотические типы данных.

Метод GetType() возвращает объект специального класса System.Reflection.TypeInfo

$var_int = 0 $get_t = $var_int.GetType() Write-Output $get_t.GetType()

IsPublic IsSerial Name BaseType -------- -------- ---- -------- False True RuntimeType System.Reflection.TypeInfo

Рассмотрим получение данных от команды Get-Location

$var_pwd = Invoke-Command -ScriptBlock { Get-Location } Write-Output $var_pwd.GetType()

IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False PathInfo System.Object

Если сейчас вывести содержимое $var_pwd оно будет аналогичным тому, что выводит команда Get-Location.

Для краткости уберем Invoke-Command.

$var_pwd = Get-Location Write-Output $var_pwd

Drive : C Provider : Microsoft.PowerShell.Core\FileSystem ProviderPath : C:\sandbox Path : C:\sandbox

Если теперь конвертировать $var_pwd в строку, результат будет сильно отличаться

Write-Output $var_pwd.ToString()

C:\sandbox

Чтобы из объекта PathInfo вытащить название диска нужно выполнить следующую команду.

Write-Output $var_pwd.Drive.Name

C

Метод GetType() нельзя применить к объекту типа $null

$var_null = $null Write-Output $var_null.GetType()

You cannot call a method on a null-valued expression. At C:\get_type_demo.ps1:9 char:1 + Write-Output $var_null.GetType() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull

В других языках

Article author: Andrei Olegovich

Related articles
Windows
PowerShell
Alias
Calling REST API
Users
Network
Install
Files
Functions
Loops
ExecutionPolicy
if
GetType()
param

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: