如何使用传递的字符串进行转换?

Tre*_*nan 4 string powershell types casting dynamic

这更像是一次学习练习,但我希望这会有所帮助.

我想创建一个这样的函数:

function array_to_array ($stuff, $new_type){
    $new_stuff = $stuff -as $new_type
    $new_stuff 
}
Run Code Online (Sandbox Code Playgroud)

我在传递字符串或甚至[char]是new_type等值时遇到问题.我想我需要做一些事情,$type = [char]但我想尽可能保持基于字符串的?

反正有没有这样做?比如激活一个字符串?

man*_*lds 6

你可以做:

[type] $new_type = "string"
Run Code Online (Sandbox Code Playgroud)

在功能上,它将是:

function array_to_array ($stuff, [type]$new_type){
    $new_stuff = $stuff -as $new_type
    $new_stuff 
}

array_to_array 1 "string"
Run Code Online (Sandbox Code Playgroud)