I'm trying to get the following code to work that tests for existence of a variable to a pipe, which is a simplification of the real code I want to execute that contains other code inside the script block, but this demonstrates the problem:
( if defined some_variable echo ok ) | more
echo was unexpected at this time
It gives me the message "echo was unexpected at this time." Quoting the with parentheses after the "if" statement doesn't fix the problem, it just complains about the parentheses
( if defined some_variable ( echo ok ) ) | more
( was unexpected at this time.
Both variations of the "if" statement will work when not in the code block being piped.
if defined some_variable echo ok
ok
if defined some_variable ( echo ok )
ok
Additionally I can execute the code block but output to a file and that works to capture the output of the script block, particularly even with multiple lines of code in the script-block:
( if ok defined some_variable echo ok ) > some_text_file.txt
This style of "if" works inside the script-block-to-pipe structure :
( if 1==1 echo ok ) | more
ok
( if NOT 1==2 echo ok ) | more
ok
But I'm not understanding why the existence test with the 'defined' keyword completely bombs this piping structure.
My final goal is to get the following kind of code to work in batch script (which has more stuff it's doing than the sample below), but the problem boils down to the simplification mentioned at the beginning that bombs. The below code will work as a batch script to echo output to command prompt and log file, but variable checks in the script block destroy it.
(
echo some_stuff_like_a_program_header
#test existence of a variable and if not defined earlier in script then echo some stuff
if NOT defined some_variable then_alert_user_with_error_msg
if some_variable==some_value (do_some_stuff) else (do_other_stuff)
) | powershell.exe -command '& { $input | tee-object -file out.log }'
Aucun commentaire:
Enregistrer un commentaire