'Powershell reevaluate string to array
i have a number of strings like this this that i would like powershell to reevaluate\convert to an array (like what would happen if you just wrote the same code in ISE without the single quotes).
$String = '@("a value","b value","c value")'
Is there a easier way to do this than stripping the '@' & '()' out of the string and using -split?
Thanks for the help in advance.
Solution 1:[1]
As long as the string contains a valid expression, you can use the [scriptblock]::Create(..) method:
$String = '@("a value","b value","c value")'
& ([scriptblock]::Create($String))
Invoke-Expression would also work but it's better to avoid it whenever possible as Ash pointed out.
Following zett42's nice feedback, with script block we can validate that arbitrary code execution is forbidden with CheckRestrictedLanguage.
In below example, Write-Host is an allowed command and a string containing only 'Write-Host "Hello world!"' would not throw an exception however, assignment statements or any other command not listed in $allowedCommands will throw an exception and the script block will not be executed.
$String = @'
Write-Host "Hello world!"
$stream = [System.Net.Sockets.TcpClient]::new('google.com', 80).GetStream()
'@
[string[]] $allowedCommands = 'Write-Host'
[string[]] $allowedVaribales = ''
[bool] $allowEnvVaribales = $false
try
{
$scriptblock = [scriptblock]::Create($String)
$scriptblock.CheckRestrictedLanguage(
$allowedCommands, $allowedVaribales, $allowEnvVaribales
)
& $scriptblock
}
catch
{
Write-Warning $_.Exception.Message
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
