简体   繁体   中英

how to specify a variable type in write-host using powershell

If I've a variable called $number and I've the following Cmdlet:

Write-host "The final number is $number"

Is there a method to set it to integer within the write-host Cmdlet.

I'm not sure what you are trying to accomplish.

If we do this:

$numberAsString = '1'
$number.GetType()

then the output of GetType() will be a string type. If instead we do this:

$numberAsInteger = 1
$number.GetType()

then the output of GetType() will be an integer type.

You can also do the following (this example doesn't really make sense when the assignment is explicit, but as was pointed out in the comments this can be useful if you are accepting user provided values):

[int]$number = '1'

This will now be an integer even though you assigned the value as a string. But none of this seems to matter for the output of write-host. For example you can do the following:

$number = '2'
Write-Host ('The final number is ' + ([int]$number))

This will work, but the output will be the same, and $number would still be a string type in this case.

Very unclear what you're asking, but taking your question literally then yes, you can:

Write-host "The final number is $([int]$number = 42)"
# OUTPUT:
# The final number is 42

If you mean "convert to int" then yes, this is also possible:

$number = 12.34
Write-host "The final number is $([int]$number)"
# OUTPUT:
# The final number is 12

To insert an integer in a string you can use:

write-host 'The final number is {0}' -f ([int]$Number)

or

write-host "The final number is $([int]$Number)"

In both cases the $Number is converted to [int] before the string is formed. But when the string is being formed the [int]$Number ist cast .toString() anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM