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

Введение

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

Пример

$myVar = 42 $myVar.GetType()

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

Если нужно получить только тип, поможет аттрибут FullName

$n = 5 $n.GetType().FullName

System.Int32

Типы данных

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

$var_int = 0 $var_long = 2147483648 $var_float = 1.0 $var_str = "aredel.com" $var_bool = $true $var_arr = 1, 2, 3, 4 $var_hash = @{ url = "heihei.website" 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

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

Автор статьи: Андрей Олегович