1

I am new to PowerShell, and a senior colleague at work stated I should use explicit data types in PowerShell. For example:

[hashtable]$hash = @{"Color" = "Red"; "Food" = "Pizza"}
[string[]]$stringArray = "a", "b", "c", "d"
[int]$integer = 14

Even with objects:

[System.Diagnostics.Process[]]$processArray = Get-Process
[System.ServiceProcess.ServiceController[]]$services = Get-Service

Is this a requirement? Can someone point out any benefits of using explicit data types in PowerShell?

1
  • Seems to me the only person this is benefiting, is your colleague. :) Commented Oct 30, 2019 at 10:38

2 Answers 2

1

As always... it depends.

In most cases, you don't need to explicitly specify the data types since if you omit the type the compiler determines it for you. Here an example:

enter image description here

However, there are situations where you want to specify the type. For example: If you assign the return type of a cmdlet to a variable but don't know whether the cmdlet return one ore more elements, you might want to declare the variable to be an array....

In short: I would avoid it if you don't need it due to readability.

Sign up to request clarification or add additional context in comments.

Comments

0

I have a different opinion. If you are writing functions in Powershell it is better to specify data types as it is another level of validation on the parameters passed to the function.

In the past I've cast the results of a function call to [array] so that I'm guaranteed to have access to array methods and properties even if there is only a single result.

[array] $Proc = Get-Process Z*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.