I'm trying to read out parameters out of a ps1-file with a Powershell script. (Run with powershell inputfile.ps1 which is calling evaluation.ps1) The input file looks like this:
$a=5
$b=""
$c=
$d=555
Unfortunately it's seems impossible to detect the not existing variable 'c' with the conventional methods e.g., $null, -eq "",'', -is [string] or similar methods. This ends up that my Powershell script automatically uses the next value from variable 'd'. So in the end I get this information:
echo "$a"
5
echo "$b"
echo "$c"
555
echo "$d"
555
Is there any possibility to avoid using the value from next line or somehow detect a missing input? Unfortunately the ps1-input file should not be touched (I know when using an empty string as input like b="", all the above mentioned methods work fine).
Thanks for any help in advance.
I guess I tried all hints out of stackoverflow already here but since it's not a string but an empty input nothing works.
To spell it out: Your
.ps1script is malformed with respect to your intent, given that:despite the newline, is the same as
$c=$d=555, which by design assigns555to both$cand$d.You have two basic options if you want
$cto be$nullinstead:(a) Preprocess your file to replace a missing value after
=with$nulland then, instead of dot-sourcing it, execute the preprocessed content viaInvoke-ExpressionInvoke-Expression(which is generally to be avoided) allow execution of arbitrary code, be sure that you fully control or implicitly trust the script's content.(b) Parse your file manually, line by line, and define the variables one by one, using
Set-Variable.Implementation of (a)
Note:
The assumption is that any line that ends in
=is also a simple assignment statement, as shown in your question.The
-replaceoperation matches a line-ending=(optionally followed by whitespace only) and replaces it with verbatim=$null. This means that such variables will still be defined, but with value$null.(?m)=\s*$) and the ability to experiment with it, see this regex101.com page.Implementation of (b)
Note: