1use itertools::Itertools;
2use nu_cmd_base::hook::eval_hook;
3use nu_engine::{command_prelude::*, env_to_strings};
4use nu_path::{AbsolutePath, dots::expand_ndots_safe, expand_tilde};
5use nu_protocol::{
6 ByteStream, NuGlob, OutDest, Signals, UseAnsiColoring, did_you_mean,
7 process::{ChildProcess, PostWaitCallback},
8 shell_error::io::IoError,
9};
10use nu_system::{ForegroundChild, kill_by_pid, prepare_background_command};
11use nu_utils::IgnoreCaseExt;
12use pathdiff::diff_paths;
13#[cfg(windows)]
14use std::os::windows::process::CommandExt;
15use std::{
16 borrow::Cow,
17 ffi::{OsStr, OsString},
18 io::Write,
19 path::{Path, PathBuf},
20 process::Stdio,
21 sync::Arc,
22 thread,
23};
24
25#[derive(Clone)]
26pub struct External;
27
28impl Command for External {
29 fn name(&self) -> &str {
30 "run-external"
31 }
32
33 fn description(&self) -> &str {
34 "Runs external command."
35 }
36
37 fn extra_description(&self) -> &str {
38 "All externals are run with this command, whether you call it directly with `run-external external` or use `external` or `^external`.
39If you create a custom command with this name, that will be used instead."
40 }
41
42 fn signature(&self) -> nu_protocol::Signature {
43 Signature::build(self.name())
44 .input_output_types(vec![(Type::Any, Type::Any)])
45 .rest(
46 "command",
47 SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Any]),
48 "External command to run, with arguments.",
49 )
50 .category(Category::System)
51 }
52
53 fn run(
54 &self,
55 engine_state: &EngineState,
56 stack: &mut Stack,
57 call: &Call,
58 input: PipelineData,
59 ) -> Result<PipelineData, ShellError> {
60 let cwd = engine_state.cwd(Some(stack))?;
61 let rest = call.rest::<Value>(engine_state, stack, 0)?;
62 let name_args = rest.split_first().map(|(x, y)| (x, y.to_vec()));
63
64 let Some((name, mut call_args)) = name_args else {
65 return Err(ShellError::MissingParameter {
66 param_name: "no command given".into(),
67 span: call.head,
68 });
69 };
70
71 let name_str: Cow<str> = match &name {
72 Value::Glob { val, .. } => Cow::Borrowed(val),
73 Value::String { val, .. } => Cow::Borrowed(val),
74 Value::List { vals, .. } => {
75 let Some((first, args)) = vals.split_first() else {
76 return Err(ShellError::MissingParameter {
77 param_name: "external command given as list empty".into(),
78 span: call.head,
79 });
80 };
81 call_args.splice(..0, args.to_vec());
83 first.coerce_str()?
84 }
85 _ => Cow::Owned(name.clone().coerce_into_string()?),
86 };
87
88 let expanded_name = match &name {
89 Value::Glob { no_expand, .. } if !*no_expand => {
91 expand_ndots_safe(expand_tilde(&*name_str))
92 }
93 _ => Path::new(&*name_str).to_owned(),
94 };
95
96 let paths = nu_engine::env::path_str(engine_state, stack, call.head).unwrap_or_default();
97
98 let pathext_script_in_windows = if cfg!(windows) {
112 if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) {
113 let ext = executable
114 .extension()
115 .unwrap_or_default()
116 .to_string_lossy()
117 .to_uppercase();
118
119 !["COM", "EXE", "BAT", "CMD", "PS1"]
120 .iter()
121 .any(|c| *c == ext)
122 } else {
123 false
124 }
125 } else {
126 false
127 };
128
129 let (potential_powershell_script, path_to_ps1_executable) = if cfg!(windows) {
131 if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) {
132 let ext = executable
133 .extension()
134 .unwrap_or_default()
135 .to_string_lossy()
136 .to_uppercase();
137 (ext == "PS1", Some(executable))
138 } else {
139 (false, None)
140 }
141 } else {
142 (false, None)
143 };
144
145 let executable = if cfg!(windows)
149 && (is_cmd_internal_command(&name_str) || pathext_script_in_windows)
150 {
151 PathBuf::from("cmd.exe")
152 } else if cfg!(windows) && potential_powershell_script && path_to_ps1_executable.is_some() {
153 PathBuf::from("powershell.exe")
157 } else {
158 let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) else {
161 return Err(command_not_found(
162 &name_str,
163 call.head,
164 engine_state,
165 stack,
166 &cwd,
167 ));
168 };
169 executable
170 };
171
172 let mut command = std::process::Command::new(&executable);
174
175 command.current_dir(cwd);
177
178 let envs = env_to_strings(engine_state, stack)?;
180 command.env_clear();
181 command.envs(envs);
182
183 let args = eval_external_arguments(engine_state, stack, call_args)?;
185 #[cfg(windows)]
186 if is_cmd_internal_command(&name_str) || pathext_script_in_windows {
187 command.args(["/D", "/C", &expanded_name.to_string_lossy()]);
191 for arg in &args {
192 command.raw_arg(escape_cmd_argument(arg)?);
193 }
194 } else if potential_powershell_script {
195 command.args([
196 "-File",
197 &path_to_ps1_executable.unwrap_or_default().to_string_lossy(),
198 ]);
199 command.args(args.into_iter().map(|s| s.item));
200 } else {
201 command.args(args.into_iter().map(|s| s.item));
202 }
203 #[cfg(not(windows))]
204 command.args(args.into_iter().map(|s| s.item));
205
206 let stdout = stack.stdout();
216 let stderr = stack.stderr();
217 let merged_stream = if matches!(stdout, OutDest::Pipe) && matches!(stderr, OutDest::Pipe) {
218 let (reader, writer) =
219 os_pipe::pipe().map_err(|err| IoError::new(err, call.head, None))?;
220 command.stdout(
221 writer
222 .try_clone()
223 .map_err(|err| IoError::new(err, call.head, None))?,
224 );
225 command.stderr(writer);
226 Some(reader)
227 } else {
228 if engine_state.is_background_job()
229 && matches!(stdout, OutDest::Inherit | OutDest::Print)
230 {
231 command.stdout(Stdio::null());
232 } else {
233 command.stdout(
234 Stdio::try_from(stdout).map_err(|err| IoError::new(err, call.head, None))?,
235 );
236 }
237
238 if engine_state.is_background_job()
239 && matches!(stderr, OutDest::Inherit | OutDest::Print)
240 {
241 command.stderr(Stdio::null());
242 } else {
243 command.stderr(
244 Stdio::try_from(stderr).map_err(|err| IoError::new(err, call.head, None))?,
245 );
246 }
247
248 None
249 };
250
251 let data_to_copy_into_stdin = match input {
255 PipelineData::ByteStream(stream, metadata) => match stream.into_stdio() {
256 Ok(stdin) => {
257 command.stdin(stdin);
258 None
259 }
260 Err(stream) => {
261 command.stdin(Stdio::piped());
262 Some(PipelineData::byte_stream(stream, metadata))
263 }
264 },
265 PipelineData::Empty => {
266 if engine_state.is_mcp || stack.suppress_stdin {
268 command.stdin(Stdio::null());
269 prepare_background_command(&mut command);
270 } else {
271 command.stdin(Stdio::inherit());
272 }
273 None
274 }
275 value => {
276 command.stdin(Stdio::piped());
277 Some(value)
278 }
279 };
280
281 log::trace!("run-external spawning: {command:?}");
283
284 #[cfg(windows)]
287 let child = ForegroundChild::spawn(command);
288 #[cfg(unix)]
289 let child = ForegroundChild::spawn(
290 command,
291 engine_state.is_interactive && !stack.suppress_stdin,
294 engine_state.is_background_job(),
295 &engine_state.pipeline_externals_state,
296 );
297
298 let mut child = child.map_err(|err| {
299 let context = format!("Could not spawn foreground child: {err}");
300 IoError::new_internal(err, context)
301 })?;
302
303 if let Some(thread_job) = engine_state.current_thread_job()
304 && !thread_job.try_add_pid(child.pid())
305 {
306 kill_by_pid(child.pid().into()).map_err(|err| {
307 ShellError::Io(IoError::new_internal(
308 err,
309 "Could not spawn external stdin worker",
310 ))
311 })?;
312 }
313
314 if let Some(data) = data_to_copy_into_stdin {
316 let stdin = child.as_mut().stdin.take().expect("stdin is piped");
317 let engine_state = engine_state.clone();
318 let stack = stack.clone();
319 thread::Builder::new()
320 .name("external stdin worker".into())
321 .spawn(move || {
322 let _ = write_pipeline_data(engine_state, stack, data, stdin);
323 })
324 .map_err(|err| {
325 IoError::new_with_additional_context(
326 err,
327 call.head,
328 None,
329 "Could not spawn external stdin worker",
330 )
331 })?;
332 }
333
334 let child_pid = child.pid();
335
336 let child = ChildProcess::new(
338 child,
339 merged_stream,
340 matches!(stderr, OutDest::Pipe),
341 call.head,
342 Some(PostWaitCallback::for_job_control(
343 engine_state,
344 Some(child_pid),
345 executable
346 .as_path()
347 .file_name()
348 .and_then(|it| it.to_str())
349 .map(|it| it.to_string()),
350 )),
351 )?;
352
353 Ok(PipelineData::byte_stream(
354 ByteStream::child(child, call.head),
355 None,
356 ))
357 }
358
359 fn examples(&self) -> Vec<Example<'_>> {
360 vec![
361 Example {
362 description: "Run an external command",
363 example: r#"run-external "echo" "-n" "hello""#,
364 result: None,
365 },
366 Example {
367 description: "Redirect stdout from an external command into the pipeline",
368 example: r#"run-external "echo" "-n" "hello" | split chars"#,
369 result: None,
370 },
371 Example {
372 description: "Redirect stderr from an external command into the pipeline",
373 example: r#"run-external "nu" "-c" "print -e hello" e>| split chars"#,
374 result: None,
375 },
376 ]
377 }
378}
379
380pub fn eval_external_arguments(
382 engine_state: &EngineState,
383 stack: &mut Stack,
384 call_args: Vec<Value>,
385) -> Result<Vec<Spanned<OsString>>, ShellError> {
386 let cwd = engine_state.cwd(Some(stack))?;
387 let mut args: Vec<Spanned<OsString>> = Vec::with_capacity(call_args.len());
388
389 for arg in call_args {
390 let span = arg.span();
391 match arg {
392 Value::Glob { val, no_expand, .. } if !no_expand => args.extend(
394 expand_glob(
395 &val,
396 cwd.as_std_path(),
397 span,
398 engine_state.signals().clone(),
399 )?
400 .into_iter()
401 .map(|s| s.into_spanned(span)),
402 ),
403 other => args
404 .push(OsString::from(coerce_into_string(engine_state, other)?).into_spanned(span)),
405 }
406 }
407 Ok(args)
408}
409
410fn coerce_into_string(engine_state: &EngineState, val: Value) -> Result<String, ShellError> {
413 match val {
414 Value::List { .. } => Err(ShellError::CannotPassListToExternal {
415 arg: String::from_utf8_lossy(engine_state.get_span_contents(val.span())).into_owned(),
416 span: val.span(),
417 }),
418 Value::Glob { val, .. } => Ok(val),
419 _ => val.coerce_into_string(),
420 }
421}
422
423fn expand_glob(
429 arg: &str,
430 cwd: &Path,
431 span: Span,
432 signals: Signals,
433) -> Result<Vec<OsString>, ShellError> {
434 if !nu_glob::is_glob_with_backend(arg) {
437 let path = expand_ndots_safe(expand_tilde(arg));
438 return Ok(vec![path.into()]);
439 }
440
441 let glob = NuGlob::Expand(arg.to_owned()).into_spanned(span);
444 if let Ok((prefix, matches)) = nu_engine::glob_from(&glob, cwd, span, None, signals.clone()) {
445 let mut result: Vec<OsString> = vec![];
446
447 for m in matches {
448 signals.check(&span)?;
449 if let Ok(arg) = m {
450 let arg = resolve_globbed_path_to_cwd_relative(arg, prefix.as_ref(), cwd);
451 result.push(arg.into());
452 } else {
453 result.push(arg.into());
454 }
455 }
456
457 if result.is_empty() {
460 result.push(arg.into());
461 }
462
463 Ok(result)
464 } else {
465 Ok(vec![arg.into()])
466 }
467}
468
469fn resolve_globbed_path_to_cwd_relative(
470 path: PathBuf,
471 prefix: Option<&PathBuf>,
472 cwd: &Path,
473) -> PathBuf {
474 if let Some(prefix) = prefix {
475 if let Ok(remainder) = path.strip_prefix(prefix) {
476 let new_prefix = if let Some(pfx) = diff_paths(prefix, cwd) {
477 pfx
478 } else {
479 prefix.to_path_buf()
480 };
481 new_prefix.join(remainder)
482 } else {
483 path
484 }
485 } else {
486 path
487 }
488}
489
490fn write_pipeline_data(
498 mut engine_state: EngineState,
499 mut stack: Stack,
500 data: PipelineData,
501 mut writer: impl Write,
502) -> Result<(), ShellError> {
503 if let PipelineData::ByteStream(stream, ..) = data {
504 stream.write_to(writer)?;
505 } else if let PipelineData::Value(Value::Binary { val, .. }, ..) = data {
506 writer
507 .write_all(&val)
508 .map_err(|err| IoError::new_internal(err, "Could not write pipeline data"))?;
509 } else {
510 stack.start_collect_value();
511
512 Arc::make_mut(&mut engine_state.config).use_ansi_coloring = UseAnsiColoring::False;
514
515 let output =
517 crate::Table.run(&engine_state, &mut stack, &Call::new(Span::unknown()), data)?;
518
519 for value in output {
521 let bytes = value.coerce_into_binary()?;
522 writer
523 .write_all(&bytes)
524 .map_err(|err| IoError::new_internal(err, "Could not write pipeline data"))?;
525 }
526 }
527 Ok(())
528}
529
530pub fn command_not_found(
532 name: &str,
533 span: Span,
534 engine_state: &EngineState,
535 stack: &mut Stack,
536 cwd: &AbsolutePath,
537) -> ShellError {
538 if let Some(hook) = &stack.get_config(engine_state).hooks.command_not_found {
540 let mut stack = stack.start_collect_value();
541 let canary = "ENTERED_COMMAND_NOT_FOUND";
544 if stack.has_env_var(engine_state, canary) {
545 return ShellError::ExternalCommand {
546 label: format!(
547 "Command {name} not found while running the `command_not_found` hook"
548 ),
549 help: "Make sure the `command_not_found` hook itself does not use unknown commands"
550 .into(),
551 span,
552 };
553 }
554 stack.add_env_var(canary.into(), Value::bool(true, Span::unknown()));
555
556 let output = eval_hook(
557 &mut engine_state.clone(),
558 &mut stack,
559 None,
560 vec![("cmd_name".into(), Value::string(name, span))],
561 hook,
562 "command_not_found",
563 );
564
565 stack.remove_env_var(engine_state, canary);
567
568 match output {
569 Ok(PipelineData::Value(Value::String { val, .. }, ..)) => {
570 return ShellError::ExternalCommand {
571 label: format!("Command `{name}` not found"),
572 help: val,
573 span,
574 };
575 }
576 Err(err) => {
577 return err;
578 }
579 _ => {
580 }
582 }
583 }
584
585 if let Some(replacement) = crate::removed_commands().get(&name.to_lowercase()) {
587 return ShellError::RemovedCommand {
588 removed: name.to_lowercase(),
589 replacement: replacement.clone(),
590 span,
591 };
592 }
593
594 let help = (|| {
596 if let Some(module) = engine_state.which_module_has_decl(name.as_bytes(), &[]) {
600 let module = String::from_utf8_lossy(module);
601
602 let full_name = format!("{module} {name}");
604 if engine_state.find_decl(full_name.as_bytes(), &[]).is_some() {
605 return format!("Did you mean `{full_name}`?");
606 }
607
608 return format!(
609 "A command with that name exists in module `{module}`. Try importing it with `use`"
610 );
611 }
612
613 let signatures = engine_state.get_signatures_and_declids(false);
615 if let Some((last, others)) = signatures
616 .iter()
617 .map(|(sig, _)| sig)
618 .filter(|sig| {
619 let name = name.to_folded_case(); sig.name
621 .to_folded_case()
622 .split_ascii_whitespace() .contains(name.as_str()) || sig
625 .search_terms
626 .iter()
627 .any(|term| term.to_folded_case() == name)
628 })
629 .map(|sig| format!("`{}`", sig.name))
630 .collect::<Vec<_>>()
631 .split_last()
632 {
633 let commands = if others.is_empty() {
634 last
635 } else {
636 &format!("{} or {last}", others.join(", "))
639 };
640
641 return format!("Did you mean {commands}?");
642 }
643
644 if let Some(cmd) = did_you_mean(signatures.iter().map(|(sig, _)| &sig.name), name) {
646 if cmd == name {
649 return "There is a built-in command with the same name".to_string();
650 }
651
652 return format!("Did you mean `{cmd}`?");
653 }
654
655 if cwd.join(name).is_file() {
657 return format!(
658 "`{name}` refers to a file that is not executable. Did you forget to set execute permissions?"
659 );
660 }
661
662 format!("`{name}` is neither a Nushell built-in or a known external command")
664 })();
665
666 ShellError::ExternalCommand {
667 label: format!("Command `{name}` not found"),
668 help,
669 span,
670 }
671}
672
673pub fn which(name: impl AsRef<OsStr>, paths: &str, cwd: &Path) -> Option<PathBuf> {
683 #[cfg(windows)]
684 let paths = format!("{};{}", cwd.display(), paths);
685 which::which_in(name, Some(paths), cwd).ok()
686}
687
688fn is_cmd_internal_command(name: &str) -> bool {
691 const COMMANDS: &[&str] = &[
692 "ASSOC", "CLS", "ECHO", "FTYPE", "MKLINK", "PAUSE", "START", "VER", "VOL",
693 ];
694 COMMANDS.iter().any(|cmd| cmd.eq_ignore_ascii_case(name))
695}
696
697fn has_cmd_special_character(s: impl AsRef<[u8]>) -> bool {
699 s.as_ref()
700 .iter()
701 .any(|b| matches!(b, b'<' | b'>' | b'&' | b'|' | b'^'))
702}
703
704#[cfg_attr(not(windows), allow(dead_code))]
706fn escape_cmd_argument(arg: &Spanned<OsString>) -> Result<Cow<'_, OsStr>, ShellError> {
707 let Spanned { item: arg, span } = arg;
708 let bytes = arg.as_encoded_bytes();
709 if bytes.iter().any(|b| matches!(b, b'\r' | b'\n' | b'%')) {
710 Err(ShellError::ExternalCommand {
712 label:
713 "Arguments to CMD internal commands cannot contain new lines or percent signs '%'"
714 .into(),
715 help: "some characters currently cannot be securely escaped".into(),
716 span: *span,
717 })
718 } else if bytes.contains(&b'"') {
719 if bytes.iter().filter(|b| **b == b'"').count() == 2
722 && bytes.starts_with(b"\"")
723 && bytes.ends_with(b"\"")
724 {
725 Ok(Cow::Borrowed(arg))
726 } else {
727 Err(ShellError::ExternalCommand {
728 label: "Arguments to CMD internal commands cannot contain embedded double quotes"
729 .into(),
730 help: "this case currently cannot be securely handled".into(),
731 span: *span,
732 })
733 }
734 } else if bytes.contains(&b' ') || has_cmd_special_character(bytes) {
735 let mut new_str = OsString::new();
737 new_str.push("\"");
738 new_str.push(arg);
739 new_str.push("\"");
740 Ok(Cow::Owned(new_str))
741 } else {
742 Ok(Cow::Borrowed(arg))
744 }
745}
746
747#[cfg(test)]
748mod test {
749 use super::*;
750 use nu_test_support::{fs::Stub, playground::Playground};
751
752 #[test]
753 fn test_expand_glob() {
754 Playground::setup("test_expand_glob", |dirs, play| {
755 play.with_files(&[Stub::EmptyFile("a.txt"), Stub::EmptyFile("b.txt")]);
756
757 let cwd = dirs.test().as_std_path();
758
759 let actual = expand_glob("*.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
760 let expected = &["a.txt", "b.txt"];
761 assert_eq!(actual, expected);
762
763 let actual = expand_glob("./*.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
764 assert_eq!(actual, expected);
765
766 let actual = expand_glob("'*.txt'", cwd, Span::test_data(), Signals::empty()).unwrap();
767 let expected = &["'*.txt'"];
768 assert_eq!(actual, expected);
769
770 let actual = expand_glob(".", cwd, Span::test_data(), Signals::empty()).unwrap();
771 let expected = &["."];
772 assert_eq!(actual, expected);
773
774 let actual = expand_glob("./a.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
775 let expected = &["./a.txt"];
776 assert_eq!(actual, expected);
777
778 let actual = expand_glob("[*.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
779 let expected = &["[*.txt"];
780 assert_eq!(actual, expected);
781
782 let actual =
783 expand_glob("~/foo.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
784 let home = dirs::home_dir().expect("failed to get home dir");
785 let expected: Vec<OsString> = vec![home.join("foo.txt").into()];
786 assert_eq!(actual, expected);
787 })
788 }
789
790 #[test]
791 fn test_write_pipeline_data() {
792 let mut engine_state = EngineState::new();
793 let stack = Stack::new();
794 let cwd = std::env::current_dir()
795 .unwrap()
796 .into_os_string()
797 .into_string()
798 .unwrap();
799
800 engine_state.add_env_var("PWD".into(), Value::string(cwd, Span::test_data()));
802
803 let mut buf = vec![];
804 let input = PipelineData::empty();
805 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
806 assert_eq!(buf, b"");
807
808 let mut buf = vec![];
809 let input = PipelineData::value(Value::string("foo", Span::test_data()), None);
810 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
811 assert_eq!(buf, b"foo");
812
813 let mut buf = vec![];
814 let input = PipelineData::value(Value::binary(b"foo", Span::test_data()), None);
815 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
816 assert_eq!(buf, b"foo");
817
818 let mut buf = vec![];
819 let input = PipelineData::byte_stream(
820 ByteStream::read(
821 b"foo".as_slice(),
822 Span::test_data(),
823 Signals::empty(),
824 ByteStreamType::Unknown,
825 ),
826 None,
827 );
828 write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
829 assert_eq!(buf, b"foo");
830 }
831}
832
833#[cfg(test)]
836mod background_isolation_tests {
837 use nu_system::prepare_background_command;
838 use std::process::{Command, Stdio};
839
840 #[cfg(unix)]
841 #[test]
842 fn setsid_removes_controlling_terminal() {
843 let mut cmd = Command::new("sh");
844 cmd.args([
846 "-c",
847 "(exec 3>/dev/tty) 2>/dev/null && echo has_tty || echo no_tty",
848 ])
849 .stdin(Stdio::null())
850 .stdout(Stdio::piped())
851 .stderr(Stdio::null());
852 prepare_background_command(&mut cmd);
853
854 let output = cmd.output().expect("sh should run");
855 assert_eq!(
856 String::from_utf8_lossy(&output.stdout).trim(),
857 "no_tty",
858 "child must not retain a controlling terminal after setsid"
859 );
860 }
861
862 #[cfg(windows)]
863 #[test]
864 fn create_no_window_has_no_console_window() {
865 let mut cmd = Command::new("powershell.exe");
873 cmd.args([
874 "-NoProfile",
875 "-NonInteractive",
876 "-Command",
877 concat!(
878 "Add-Type -Namespace NuBg -Name Native -MemberDefinition '",
879 "[DllImport(\"kernel32.dll\")] public static extern System.IntPtr GetConsoleWindow();",
880 "'; ",
881 "if ([NuBg.Native]::GetConsoleWindow() -eq [System.IntPtr]::Zero) { ",
882 "[Console]::Out.Write('no_console') ",
883 "} else { ",
884 "[Console]::Out.Write('has_console') ",
885 "}",
886 ),
887 ])
888 .stdin(Stdio::null())
889 .stdout(Stdio::piped())
890 .stderr(Stdio::piped());
891 prepare_background_command(&mut cmd);
892
893 let output = cmd.output().expect("powershell should run");
894 let stdout = String::from_utf8_lossy(&output.stdout);
895 let stderr = String::from_utf8_lossy(&output.stderr);
896 let token = stdout
897 .split_whitespace()
898 .find(|t| *t == "no_console" || *t == "has_console")
899 .unwrap_or("");
900 assert_eq!(
901 token, "no_console",
902 "child must have no console window under CREATE_NO_WINDOW; stdout={stdout:?} stderr={stderr}"
903 );
904 }
905}