Is it possible to extract and run PowerShell code out of a text file without creating a new file?
I have some files (not .ps1 files) containing lines of PowerShell intermixed with lines of other text. I have a function that successfully extracts the PowerShell into a string variable, $code. In testing I can make it as simple as:
$code = get-content .\onlycode.txt
I want to then run the lines I extracted, but I cannot for the life of me figure out how if there is more than a single line. I've tried:
- & $code --> This tells me [contents of $code] is not recognized as a cmdlet, function, etc.
- & {$code} --> This just parrots back $code as text including newlines
- Invoke-command -scriptblock {$code} --> This just parrots back $code as text including newlines
- Invoke-command -scriptblock {& {$code}} --> This just parrots back $code as text without newlines
- Invoke-expression $code --> "Cannot convert 'system.object' to the type 'system.string'"
- Invoke-expression "& {$code}" --> "missing closing '}' in statement block" ??
What am I doing wrong? Is this not possible?
Thanks.