1use engine::{BytesInput, BytesOutput, Engine, Input, Output, Pipe, Terminal, VirtualPath};
18use os::runtime::ExitStatus;
19use os::windows::Windows;
20use os::{Environment, OperatingSystem};
21use pwsh_parser::{Token, TokenKind};
22
23pub struct PowerShell<'os> {
25 os: &'os Windows,
27 actor: engine::ActorId,
29 cwd: VirtualPath,
31 environment: Environment,
33 aliases: std::collections::BTreeMap<String, String>,
36 exit_request: Option<ExitStatus>,
39 history: Vec<String>,
43}
44
45impl<'os> PowerShell<'os> {
46 pub fn new(
51 os: &'os Windows,
52 actor: engine::ActorId,
53 environment: Environment,
54 ) -> Result<Self, os::OsError> {
55 let user_name = os
56 .users()
57 .get(actor.get() as u32)
58 .map(|user| user.name().to_owned())
59 .unwrap_or_else(|| "Administrator".to_owned());
60 let home: VirtualPath = format!("/Users/{user_name}").parse().expect("valid path");
61 let cwd = if os.engine().lookup(Some(actor), &home).is_ok() {
62 home
63 } else {
64 VirtualPath::root()
65 };
66 let aliases: std::collections::BTreeMap<String, String> = default_aliases()
67 .into_iter()
68 .map(|(name, target)| (name.to_owned(), target.to_owned()))
69 .collect();
70 Ok(Self {
71 os,
72 actor,
73 cwd,
74 environment,
75 aliases,
76 exit_request: None,
77 history: Vec::new(),
78 })
79 }
80
81 pub fn actor(&self) -> engine::ActorId {
83 self.actor
84 }
85
86 pub fn environment(&self) -> &Environment {
88 &self.environment
89 }
90
91 fn run_line(
93 &mut self,
94 line: &str,
95 stdin: &mut dyn Input,
96 stdout: &mut dyn Output,
97 stderr: &mut dyn Output,
98 ) -> ExitStatus {
99 let lexed = pwsh_parser::tokenize(line);
100 let mut last_status = ExitStatus::SUCCESS;
101 for statement in split_statements(&lexed.tokens) {
102 last_status = self.run_pipeline(&statement, line, stdin, stdout, stderr);
103 }
104 last_status
105 }
106
107 fn run_pipeline(
109 &mut self,
110 tokens: &[Token],
111 source: &str,
112 stdin: &mut dyn Input,
113 stdout: &mut dyn Output,
114 stderr: &mut dyn Output,
115 ) -> ExitStatus {
116 let stages = split_pipeline(tokens);
117 if stages.len() == 1 {
118 return self.run_stage(&stages[0], source, stdin, stdout, stderr);
119 }
120 let pipes: Vec<Pipe> = (0..stages.len() - 1).map(|_| Pipe::new()).collect();
125 let mut last_status = ExitStatus::SUCCESS;
126 for (index, stage) in stages.iter().enumerate() {
127 let is_last = index == stages.len() - 1;
128 if is_last {
129 let mut pipe_in = pipes[index - 1].input();
130 last_status = self.run_stage(stage, source, &mut pipe_in, stdout, stderr);
131 } else {
132 let mut pipe_out = pipes[index].output();
133 let pipe_in = if index == 0 {
134 &mut *stdin
135 } else {
136 &mut pipes[index - 1].input()
137 };
138 last_status = self.run_stage(stage, source, pipe_in, &mut pipe_out, stderr);
139 }
140 }
141 last_status
142 }
143
144 fn run_stage(
146 &mut self,
147 tokens: &[Token],
148 source: &str,
149 stdin: &mut dyn Input,
150 stdout: &mut dyn Output,
151 stderr: &mut dyn Output,
152 ) -> ExitStatus {
153 let mut argv = Vec::new();
154 let mut stdin_source: Option<BytesInput> = None;
155 let mut captured = BytesOutput::new();
156 let mut stdout_redirect: Option<(String, bool)> = None;
157 let mut string_expression = false;
161 let mut first_word_seen = false;
162
163 let mut index = 0;
164 while index < tokens.len() {
165 let token = &tokens[index];
166 if !first_word_seen
167 && matches!(
168 token.kind,
169 TokenKind::StringLiteral | TokenKind::StringExpandable
170 )
171 {
172 string_expression = true;
173 }
174 match token.kind {
175 TokenKind::Operator(_) if is_redirect(token, source) => {
176 let operator = token.text(source);
178 index += 1;
179 while index < tokens.len()
181 && matches!(
182 tokens[index].kind,
183 TokenKind::Whitespace | TokenKind::Newline
184 )
185 {
186 index += 1;
187 }
188 let target = tokens
189 .get(index)
190 .map(|t| word_text(t, source, &self.environment).unwrap_or_default())
191 .unwrap_or_default();
192 if operator == "<" {
193 stdin_source = Some(read_file(self, &target));
194 } else {
195 stdout_redirect = Some((target, operator == ">>"));
196 }
197 }
198 _ => {
199 if let Some(word) = word_text(token, source, &self.environment) {
200 argv.push(word);
201 first_word_seen = true;
202 }
203 }
204 }
205 index += 1;
206 }
207
208 if argv.is_empty() {
209 return ExitStatus::SUCCESS;
210 }
211
212 if string_expression {
215 let value = argv.join(" ");
216 if let Some((path, append)) = stdout_redirect {
217 if let Err(error) =
218 self.write_redirect(&path, format!("{value}\n").as_bytes(), append)
219 {
220 let _ = stderr.write(format!("{error}\n").as_bytes());
221 return ExitStatus::FAILURE;
222 }
223 } else {
224 let _ = stdout.write(format!("{value}\n").as_bytes());
225 }
226 return ExitStatus::SUCCESS;
227 }
228
229 let argv = {
233 let mut normalized_argv = argv;
234 if normalized_argv.len() == 1 {
235 let first = normalized_argv[0].clone();
236 let lower = first.to_lowercase();
237 for prefix in ["cd", "chdir", "sl"] {
238 if lower.starts_with(prefix) && lower.len() > prefix.len() {
239 let rest = first[prefix.len()..].to_owned();
240 if rest.starts_with('\\')
241 || rest.starts_with('/')
242 || rest.starts_with('.')
243 || rest.starts_with(':')
244 {
245 normalized_argv = vec![prefix.to_string(), rest];
246 break;
247 }
248 }
249 }
250 }
251 normalized_argv
252 };
253
254 let command = argv[0].clone();
255 let resolved = self
258 .aliases
259 .get(&command.to_lowercase())
260 .cloned()
261 .unwrap_or_else(|| command.clone());
262 let effective_stdin: &mut dyn Input = match &mut stdin_source {
263 Some(input) => input,
264 None => stdin,
265 };
266 let effective_stdout: &mut dyn Output = if stdout_redirect.is_some() {
267 &mut captured
268 } else {
269 stdout
270 };
271
272 if let Some(status) =
274 self.try_builtin(&resolved, &argv, effective_stdin, effective_stdout, stderr)
275 {
276 if let Some((path, append)) = stdout_redirect
277 && let Err(error) = self.write_redirect(&path, &captured.into_bytes(), append)
278 {
279 let _ = stderr.write(format!("{command}: {error}\n").as_bytes());
280 return ExitStatus::FAILURE;
281 }
282 return status;
283 }
284
285 let status = match crate::windows_core::run_external(
289 self.os,
290 self.actor,
291 &self.cwd,
292 &self.environment,
293 &command,
294 &argv,
295 effective_stdin,
296 effective_stdout,
297 stderr,
298 ) {
299 Some(status) => status,
300 None => {
301 let _ = stderr.write(format!("{command}: The term '{command}' is not recognized as the name of a cmdlet, function, script file, or operable program.\n").as_bytes());
302 ExitStatus::NOT_FOUND
303 }
304 };
305 if let Some((path, append)) = stdout_redirect
306 && let Err(error) = self.write_redirect(&path, &captured.into_bytes(), append)
307 {
308 let _ = stderr.write(format!("{command}: {error}\n").as_bytes());
309 return ExitStatus::FAILURE;
310 }
311 status
312 }
313
314 fn write_redirect(
317 &self,
318 path_str: &str,
319 bytes: &[u8],
320 append: bool,
321 ) -> Result<(), os::OsError> {
322 crate::windows_core::write_redirect(self.os, self.actor, &self.cwd, path_str, bytes, append)
323 }
324
325 fn resolve_path(&self, argument: &str) -> Result<VirtualPath, os::OsError> {
330 crate::windows_core::resolve_path(&self.cwd, argument)
331 }
332
333 fn display_path(&self, path: &engine::VirtualPath) -> String {
335 crate::windows_core::display_path(path)
336 }
337
338 fn display_path_of(&self, argument: &str) -> String {
340 match self.resolve_path(argument) {
341 Ok(path) => self.display_path(&path),
342 Err(_) => argument.to_owned(),
343 }
344 }
345
346 fn try_builtin(
348 &mut self,
349 name: &str,
350 argv: &[String],
351 stdin: &mut dyn Input,
352 stdout: &mut dyn Output,
353 stderr: &mut dyn Output,
354 ) -> Option<ExitStatus> {
355 let _ = stdin;
356 match name.to_lowercase().as_str() {
357 "set-location" => Some(self.builtin_cd(argv, stderr)),
358 "get-location" => Some(self.builtin_pwd(stdout)),
359 "get-childitem" => Some(self.builtin_ls(argv, stdout, stderr)),
360 "get-content" => Some(self.builtin_cat(argv, stdout, stderr)),
361 "write-output" => Some(self.builtin_echo(argv, stdout)),
362 "clear-host" => Some(self.builtin_clear_host(stdout)),
363 "get-alias" => Some(self.builtin_get_alias(argv, stdout, stderr)),
364 "set-alias" => Some(self.builtin_set_alias(argv, stdout, stderr)),
365 "get-history" => Some(self.builtin_history(stdout)),
366 "get-localuser" => Some(self.builtin_get_localuser(argv, stdout, stderr)),
367 "get-localgroup" => Some(self.builtin_get_localgroup(argv, stdout, stderr)),
368 "get-service" => Some(self.builtin_get_service(argv, stdout, stderr)),
369 "get-item" => Some(self.builtin_get_item(argv, stdout, stderr)),
370 "remove-item" => Some(self.builtin_remove_item(argv, stdout, stderr)),
371 "set-content" => Some(self.builtin_set_content(argv, stdout, stderr)),
372 "copy-item" => Some(self.builtin_copy_item(argv, stdout, stderr)),
373 "move-item" => Some(self.builtin_move_item(argv, stdout, stderr)),
374 "new-item" => Some(self.builtin_new_item(argv, stdout, stderr)),
375 "get-process" => Some(self.builtin_get_process(argv, stdout, stderr)),
376 "stop-process" => Some(self.builtin_stop_process(argv, stdout, stderr)),
377 "get-itemproperty" => Some(self.builtin_get_itemproperty(argv, stdout, stderr)),
378 "set-itemproperty" => Some(self.builtin_set_itemproperty(argv, stdout, stderr)),
379 "remove-itemproperty" => Some(self.builtin_remove_itemproperty(argv, stdout, stderr)),
380 "start-sleep" => Some(self.builtin_start_sleep(argv, stderr)),
381 "get-date" => Some(self.builtin_get_date(stdout)),
382 "exit" => {
383 let code = argv
384 .get(1)
385 .and_then(|value| value.trim().parse::<i64>().ok())
386 .map_or(0, |value| u8::try_from(value & 0xFF).unwrap_or(0));
387 let status = ExitStatus::new(code);
388 self.exit_request = Some(status);
389 Some(status)
390 }
391 _ => None,
392 }
393 }
394
395 fn builtin_set_content(
402 &self,
403 argv: &[String],
404 stdout: &mut dyn Output,
405 stderr: &mut dyn Output,
406 ) -> ExitStatus {
407 let _ = stdout;
408 let mut path: Option<String> = None;
409 let mut values: Vec<String> = Vec::new();
410 let mut append = false;
411 let mut positional_value = false;
412 for argument in argv.iter().skip(1) {
413 if argument.eq_ignore_ascii_case("-Path") {
414 positional_value = false;
415 } else if argument.eq_ignore_ascii_case("-Value") {
416 positional_value = true;
417 } else if argument.eq_ignore_ascii_case("-Append") {
418 append = true;
419 } else if argument.starts_with('-') && !positional_value {
420 continue;
421 } else if path.is_none() && !positional_value {
422 path = Some(argument.clone());
423 } else {
424 values.push(argument.clone());
425 }
426 }
427 let Some(path) = path else {
428 let _ = stderr.write(
429 b"Set-Content : Cannot bind argument to parameter 'Path' because it is an empty string.\nAt line:1 char:1\n+ Set-Content\n+ ~~~~~~~~~~~\n + CategoryInfo : InvalidArgument: (Path) [], ParameterBindingException\n + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyString,Microsoft.PowerShell.Commands.SetContentCommand\n",
430 );
431 return ExitStatus::FAILURE;
432 };
433 let value = values.join("\n");
434 let mut content = value;
435 if !content.is_empty() {
436 content.push('\n');
437 }
438 match self.write_redirect(&path, content.as_bytes(), append) {
439 Ok(()) => ExitStatus::SUCCESS,
440 Err(error) => {
441 let _ = stderr.write(format!("Set-Content : {error}\n").as_bytes());
442 ExitStatus::FAILURE
443 }
444 }
445 }
446
447 fn builtin_clear_host(&self, stdout: &mut dyn Output) -> ExitStatus {
452 let _ = stdout.write(b"\x1b[3J\x1b[H\x1b[2J");
453 ExitStatus::SUCCESS
454 }
455
456 fn builtin_start_sleep(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
458 let seconds = argv
459 .iter()
460 .skip(1)
461 .find(|argument| *argument != "-Seconds")
462 .and_then(|argument| argument.trim().parse::<f64>().ok())
463 .filter(|seconds| *seconds >= 0.0);
464 let Some(seconds) = seconds else {
465 let _ = stderr.write(
466 b"Start-Sleep : Cannot bind argument to parameter 'Seconds' because it is an empty string.\n",
467 );
468 return ExitStatus::FAILURE;
469 };
470 self.os
471 .engine()
472 .advance_time(std::time::Duration::from_secs_f64(seconds));
473 ExitStatus::SUCCESS
474 }
475
476 fn builtin_get_date(&self, stdout: &mut dyn Output) -> ExitStatus {
478 let _ = stdout.write(
479 format!(
480 "{}\n",
481 os::datetime::format_timestamp(self.os.engine().time(), "%a %b %d %H:%M:%S %Y")
482 )
483 .as_bytes(),
484 );
485 ExitStatus::SUCCESS
486 }
487
488 fn builtin_copy_item(
490 &self,
491 argv: &[String],
492 stdout: &mut dyn Output,
493 stderr: &mut dyn Output,
494 ) -> ExitStatus {
495 let _ = stdout;
496 let mut recursive = false;
497 let mut operands: Vec<&String> = Vec::new();
498 for argument in argv.iter().skip(1) {
499 if argument == "-Recurse" || argument == "-r" {
500 recursive = true;
501 } else if argument.starts_with('-') {
502 continue;
503 } else {
504 operands.push(argument);
505 }
506 }
507 if operands.len() < 2 {
508 let _ = stderr.write(
509 b"Copy-Item : A positional parameter cannot be found that accepts argument ''.\n",
510 );
511 return ExitStatus::FAILURE;
512 }
513 let source_str = operands[0].clone();
514 let destination_str = operands[operands.len() - 1].clone();
515 let engine = self.os.engine();
516 let actor = Some(self.actor);
517 let source_path = match self.resolve_path(&source_str) {
518 Ok(path) => path,
519 Err(_) => {
520 let _ = stderr.write(
521 format!(
522 "Copy-Item : Cannot find path '{}' because it does not exist.\n",
523 self.display_path_of(&source_str)
524 )
525 .as_bytes(),
526 );
527 return ExitStatus::FAILURE;
528 }
529 };
530 let source_object = match engine.lookup(actor, &source_path) {
531 Ok(object) => object,
532 Err(_) => {
533 let _ = stderr.write(
534 format!(
535 "Copy-Item : Cannot find path '{}' because it does not exist.\n",
536 self.display_path_of(&source_str)
537 )
538 .as_bytes(),
539 );
540 return ExitStatus::FAILURE;
541 }
542 };
543 let destination_path = match self.resolve_path(&destination_str) {
544 Ok(path) => path,
545 Err(_) => {
546 let _ = stderr.write(
547 format!(
548 "Copy-Item : Cannot find path '{}' because it does not exist.\n",
549 self.display_path_of(&destination_str)
550 )
551 .as_bytes(),
552 );
553 return ExitStatus::FAILURE;
554 }
555 };
556 let is_directory = engine.list(actor, source_object).is_ok();
557 if is_directory && !recursive {
558 let _ = stderr.write(
559 format!(
560 "Copy-Item : Access to the path '{}' is denied.\n",
561 self.display_path(&source_path)
562 )
563 .as_bytes(),
564 );
565 return ExitStatus::FAILURE;
566 }
567 let (destination_directory, name) = match engine.lookup(actor, &destination_path) {
568 Ok(object) if engine.list(actor, object).is_ok() => {
569 let name = source_path.name().expect("source has name").to_owned();
570 (object, name)
571 }
572 Ok(_) => {
573 let name = destination_path
574 .name()
575 .expect("destination has name")
576 .to_owned();
577 let parent = destination_path
578 .parent()
579 .expect("destination has parent")
580 .clone();
581 match engine.lookup(actor, &parent) {
582 Ok(object) => (object, name),
583 Err(_) => {
584 let _ = stderr.write(
585 format!(
586 "Copy-Item : Cannot find path '{}' because it does not exist.\n",
587 self.display_path(&parent)
588 )
589 .as_bytes(),
590 );
591 return ExitStatus::FAILURE;
592 }
593 }
594 }
595 Err(_) => {
596 let name = destination_path
597 .name()
598 .expect("destination has name")
599 .to_owned();
600 let parent = destination_path
601 .parent()
602 .expect("destination has parent")
603 .clone();
604 match engine.lookup(actor, &parent) {
605 Ok(object) => (object, name),
606 Err(_) => {
607 let _ = stderr.write(
608 format!(
609 "Copy-Item : Cannot find path '{}' because it does not exist.\n",
610 self.display_path(&parent)
611 )
612 .as_bytes(),
613 );
614 return ExitStatus::FAILURE;
615 }
616 }
617 }
618 };
619 let name = match engine::Name::new(&name) {
620 Ok(name) => name,
621 Err(_) => {
622 let _ = stderr.write(b"Copy-Item : Illegal characters in path.\n");
623 return ExitStatus::FAILURE;
624 }
625 };
626 match engine.copy_object(actor, source_object, destination_directory, name) {
627 Ok(_) => ExitStatus::SUCCESS,
628 Err(error) => {
629 let _ = stderr.write(format!("Copy-Item : {error}\n").as_bytes());
630 ExitStatus::FAILURE
631 }
632 }
633 }
634
635 fn builtin_move_item(
637 &self,
638 argv: &[String],
639 stdout: &mut dyn Output,
640 stderr: &mut dyn Output,
641 ) -> ExitStatus {
642 let _ = stdout;
643 let operands: Vec<&String> = argv
644 .iter()
645 .skip(1)
646 .filter(|argument| !argument.starts_with('-'))
647 .collect();
648 if operands.len() < 2 {
649 let _ = stderr.write(
650 b"Move-Item : A positional parameter cannot be found that accepts argument ''.\n",
651 );
652 return ExitStatus::FAILURE;
653 }
654 let source_str = operands[0].clone();
655 let destination_str = operands[operands.len() - 1].clone();
656 let engine = self.os.engine();
657 let actor = Some(self.actor);
658 let source_path = match self.resolve_path(&source_str) {
659 Ok(path) => path,
660 Err(_) => {
661 let _ = stderr.write(
662 format!(
663 "Move-Item : Cannot find path '{}' because it does not exist.\n",
664 self.display_path_of(&source_str)
665 )
666 .as_bytes(),
667 );
668 return ExitStatus::FAILURE;
669 }
670 };
671 let source_object = match engine.lookup(actor, &source_path) {
672 Ok(object) => object,
673 Err(_) => {
674 let _ = stderr.write(
675 format!(
676 "Move-Item : Cannot find path '{}' because it does not exist.\n",
677 self.display_path_of(&source_str)
678 )
679 .as_bytes(),
680 );
681 return ExitStatus::FAILURE;
682 }
683 };
684 let destination_path = match self.resolve_path(&destination_str) {
685 Ok(path) => path,
686 Err(_) => {
687 let _ = stderr.write(
688 format!(
689 "Move-Item : Cannot find path '{}' because it does not exist.\n",
690 self.display_path_of(&destination_str)
691 )
692 .as_bytes(),
693 );
694 return ExitStatus::FAILURE;
695 }
696 };
697 let (destination_directory, name) = match engine.lookup(actor, &destination_path) {
698 Ok(object) if engine.list(actor, object).is_ok() => {
699 let name = source_path.name().expect("source has name").to_owned();
700 (object, name)
701 }
702 Ok(_) => {
703 let name = destination_path
704 .name()
705 .expect("destination has name")
706 .to_owned();
707 let parent = destination_path
708 .parent()
709 .expect("destination has parent")
710 .clone();
711 match engine.lookup(actor, &parent) {
712 Ok(object) => (object, name),
713 Err(_) => {
714 let _ = stderr.write(
715 format!(
716 "Move-Item : Cannot find path '{}' because it does not exist.\n",
717 self.display_path(&parent)
718 )
719 .as_bytes(),
720 );
721 return ExitStatus::FAILURE;
722 }
723 }
724 }
725 Err(_) => {
726 let name = destination_path
727 .name()
728 .expect("destination has name")
729 .to_owned();
730 let parent = destination_path
731 .parent()
732 .expect("destination has parent")
733 .clone();
734 match engine.lookup(actor, &parent) {
735 Ok(object) => (object, name),
736 Err(_) => {
737 let _ = stderr.write(
738 format!(
739 "Move-Item : Cannot find path '{}' because it does not exist.\n",
740 self.display_path(&parent)
741 )
742 .as_bytes(),
743 );
744 return ExitStatus::FAILURE;
745 }
746 }
747 }
748 };
749 let name = match engine::Name::new(&name) {
750 Ok(name) => name,
751 Err(_) => {
752 let _ = stderr.write(b"Move-Item : Illegal characters in path.\n");
753 return ExitStatus::FAILURE;
754 }
755 };
756 match engine.move_object(actor, source_object, destination_directory, Some(name)) {
757 Ok(_) => ExitStatus::SUCCESS,
758 Err(error) => {
759 let _ = stderr.write(format!("Move-Item : {error}\n").as_bytes());
760 ExitStatus::FAILURE
761 }
762 }
763 }
764
765 fn builtin_new_item(
767 &self,
768 argv: &[String],
769 stdout: &mut dyn Output,
770 stderr: &mut dyn Output,
771 ) -> ExitStatus {
772 let _ = stdout;
773 let mut item_type = "File".to_owned();
774 let mut target: Option<String> = None;
775 for argument in argv.iter().skip(1) {
776 if argument == "-ItemType" {
777 if let Some(value) = argv
778 .iter()
779 .skip(1)
780 .skip(1)
781 .find(|value| *value != "-ItemType")
782 {
783 item_type = value.to_owned();
784 }
785 } else if argument.starts_with('-') {
786 continue;
787 } else if target.is_none() {
788 target = Some(argument.clone());
789 }
790 }
791 let Some(target) = target else {
792 let _ = stderr.write(
793 b"New-Item : Cannot bind argument to parameter 'Path' because it is an empty string.\n",
794 );
795 return ExitStatus::FAILURE;
796 };
797 let path = match self.resolve_path(&target) {
798 Ok(path) => path,
799 Err(_) => {
800 let _ = stderr.write(
801 format!(
802 "New-Item : Cannot find path '{}' because it does not exist.\n",
803 self.display_path_of(&target)
804 )
805 .as_bytes(),
806 );
807 return ExitStatus::FAILURE;
808 }
809 };
810 let engine = self.os.engine();
811 let actor = Some(self.actor);
812 if engine.lookup(actor, &path).is_ok() {
813 let _ = stderr.write(
814 format!(
815 "New-Item : An item with the specified name '{}' already exists.\n",
816 self.display_path(&path)
817 )
818 .as_bytes(),
819 );
820 return ExitStatus::FAILURE;
821 }
822 let parent_path = path.parent().expect("path has parent").clone();
823 let parent = match engine.lookup(actor, &parent_path) {
824 Ok(parent) => parent,
825 Err(_) => {
826 let _ = stderr.write(
827 format!(
828 "New-Item : Cannot find path '{}' because it does not exist.\n",
829 self.display_path(&parent_path)
830 )
831 .as_bytes(),
832 );
833 return ExitStatus::FAILURE;
834 }
835 };
836 let name = path.name().expect("path has name").to_owned();
837 let name = match engine::Name::new(&name) {
838 Ok(name) => name,
839 Err(_) => {
840 let _ = stderr.write(b"New-Item : Illegal characters in path.\n");
841 return ExitStatus::FAILURE;
842 }
843 };
844 let directory = item_type.eq_ignore_ascii_case("Directory");
845 let result = if directory {
846 engine.create_directory(actor, parent, name)
847 } else {
848 engine.create_file(actor, parent, name, Some(Vec::new()))
849 };
850 match result {
851 Ok(_) => ExitStatus::SUCCESS,
852 Err(error) => {
853 let _ = stderr.write(format!("New-Item : {error}\n").as_bytes());
854 ExitStatus::FAILURE
855 }
856 }
857 }
858
859 fn builtin_get_process(
861 &self,
862 _argv: &[String],
863 stdout: &mut dyn Output,
864 stderr: &mut dyn Output,
865 ) -> ExitStatus {
866 let actor = Some(self.actor);
867 let engine = self.os.engine();
868 let processes = match self.os.processes() {
869 Ok(processes) => processes,
870 Err(error) => {
871 let _ = stderr.write(format!("Get-Process : {error}\n").as_bytes());
872 return ExitStatus::FAILURE;
873 }
874 };
875 let processes = match os::process::list(engine, actor, processes.id()) {
876 Ok(processes) => processes,
877 Err(error) => {
878 let _ = stderr.write(format!("Get-Process : {error}\n").as_bytes());
879 return ExitStatus::FAILURE;
880 }
881 };
882 let _ = stdout.write(
883 b"Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName\n------- ------ ----- ----- ------ -- -----------\n",
884 );
885 for (_, process) in processes {
886 let _ = stdout.write(
887 format!(
888 " 0 0 0 0 0.00 {:>5} {}\n",
889 process.pid, process.executable
890 )
891 .as_bytes(),
892 );
893 }
894 ExitStatus::SUCCESS
895 }
896
897 fn builtin_stop_process(
899 &self,
900 argv: &[String],
901 stdout: &mut dyn Output,
902 stderr: &mut dyn Output,
903 ) -> ExitStatus {
904 let _ = stdout;
905 let mut id: Option<u32> = None;
906 let mut name: Option<String> = None;
907 for argument in argv.iter().skip(1) {
908 if argument == "-Id" {
909 id = argv
910 .iter()
911 .skip(1)
912 .find(|value| *value != "-Id")
913 .and_then(|value| value.parse().ok());
914 } else if argument == "-Name" {
915 name = argv.iter().skip(1).find(|value| *value != "-Name").cloned();
916 }
917 }
918 let actor = Some(self.actor);
919 let engine = self.os.engine();
920 let processes = match self.os.processes() {
921 Ok(processes) => processes,
922 Err(error) => {
923 let _ = stderr.write(format!("Stop-Process : {error}\n").as_bytes());
924 return ExitStatus::FAILURE;
925 }
926 };
927 let processes = match os::process::list(engine, actor, processes.id()) {
928 Ok(processes) => processes,
929 Err(error) => {
930 let _ = stderr.write(format!("Stop-Process : {error}\n").as_bytes());
931 return ExitStatus::FAILURE;
932 }
933 };
934 let mut terminated = false;
935 for (object, process) in processes {
936 let matches = if let Some(id) = id {
937 process.pid == id
938 } else if let Some(name) = &name {
939 process.executable.eq_ignore_ascii_case(name)
940 } else {
941 false
942 };
943 if matches {
944 terminated = true;
945 let _ = engine.delete(actor, object);
946 }
947 }
948 if !terminated {
949 if let Some(id) = id {
950 let _ = stderr.write(
951 format!(
952 "Stop-Process : Cannot find a process with the process identifier {id}. Verify the process identifier and call the cmdlet again.\n"
953 )
954 .as_bytes(),
955 );
956 } else {
957 let _ = stderr.write(
958 format!(
959 "Stop-Process : Cannot find a process with the name \"{}\". Verify the process name and call the cmdlet again.\n",
960 name.as_deref().unwrap_or_default()
961 )
962 .as_bytes(),
963 );
964 }
965 return ExitStatus::FAILURE;
966 }
967 ExitStatus::SUCCESS
968 }
969
970 fn builtin_get_itemproperty(
972 &self,
973 argv: &[String],
974 stdout: &mut dyn Output,
975 stderr: &mut dyn Output,
976 ) -> ExitStatus {
977 let registry = match self.os.registry() {
978 Ok(registry) => registry,
979 Err(error) => {
980 let _ = stderr.write(format!("Get-ItemProperty : {error}\n").as_bytes());
981 return ExitStatus::FAILURE;
982 }
983 };
984 let path_arg = argv
985 .iter()
986 .skip(1)
987 .find(|argument| !argument.starts_with('-'))
988 .cloned()
989 .unwrap_or_default();
990 let (hive, path) = match Self::registry_path(&path_arg) {
991 Some(parts) => parts,
992 None => {
993 let _ = stderr.write(
994 format!(
995 "Get-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
996 )
997 .as_bytes(),
998 );
999 return ExitStatus::FAILURE;
1000 }
1001 };
1002 let actor = Some(self.actor);
1003 let key = match registry.key(actor, &hive, &path) {
1004 Ok(Some(key)) => key,
1005 _ => {
1006 let _ = stderr.write(
1007 format!(
1008 "Get-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
1009 )
1010 .as_bytes(),
1011 );
1012 return ExitStatus::FAILURE;
1013 }
1014 };
1015 let values = match registry.values(actor, key) {
1016 Ok(values) => values,
1017 Err(error) => {
1018 let _ = stderr.write(format!("Get-ItemProperty : {error}\n").as_bytes());
1019 return ExitStatus::FAILURE;
1020 }
1021 };
1022 let display = format!(
1023 "{}\\{}",
1024 os::windows::registry::RegistryState::hive_display(&hive),
1025 path.replace('/', "\\")
1026 );
1027 for value in values {
1028 let _ = stdout.write(format!("{:<18} : {}\n", value.name, value.data).as_bytes());
1029 }
1030 let _ = stdout.write(
1031 format!(
1032 "PSPath : Microsoft.PowerShell.Core\\Registry::{display}\nPSParentPath : Microsoft.PowerShell.Core\\Registry::{}\nPSParentChild : {}\nPSDrive : {}\nPSProvider : Microsoft.PowerShell.Core\\Registry\n",
1033 parent_of_display(&display),
1034 display.rsplit('\\').next().unwrap_or_default(),
1035 hive.to_uppercase()
1036 )
1037 .as_bytes(),
1038 );
1039 ExitStatus::SUCCESS
1040 }
1041
1042 fn builtin_set_itemproperty(
1044 &self,
1045 argv: &[String],
1046 stdout: &mut dyn Output,
1047 stderr: &mut dyn Output,
1048 ) -> ExitStatus {
1049 let _ = stdout;
1050 let registry = match self.os.registry() {
1051 Ok(registry) => registry,
1052 Err(error) => {
1053 let _ = stderr.write(format!("Set-ItemProperty : {error}\n").as_bytes());
1054 return ExitStatus::FAILURE;
1055 }
1056 };
1057 let path_arg = argv
1058 .iter()
1059 .skip(1)
1060 .find(|argument| !argument.starts_with('-'))
1061 .cloned()
1062 .unwrap_or_default();
1063 let (hive, path) = match Self::registry_path(&path_arg) {
1064 Some(parts) => parts,
1065 None => {
1066 let _ = stderr.write(
1067 format!(
1068 "Set-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
1069 )
1070 .as_bytes(),
1071 );
1072 return ExitStatus::FAILURE;
1073 }
1074 };
1075 let mut name: Option<String> = None;
1076 let mut value: Option<String> = None;
1077 let args: Vec<String> = argv.iter().skip(1).cloned().collect();
1078 let mut index = 0;
1079 while index < args.len() {
1080 match args[index].to_ascii_lowercase().as_str() {
1081 "-name" => {
1082 index += 1;
1083 name = args.get(index).cloned();
1084 }
1085 "-value" => {
1086 index += 1;
1087 value = args.get(index).cloned();
1088 }
1089 "-pathtype" | "-type" => {
1090 index += 1;
1091 }
1092 _ => {}
1093 }
1094 index += 1;
1095 }
1096 let (Some(name), Some(value)) = (name, value) else {
1097 let _ = stderr.write(b"Set-ItemProperty : Cannot bind argument to parameter 'Name' because it is an empty string.\n");
1098 return ExitStatus::FAILURE;
1099 };
1100 match registry.set_value(Some(self.actor), &hive, &path, &name, "REG_SZ", &value) {
1101 Ok(()) => ExitStatus::SUCCESS,
1102 Err(error) => {
1103 let _ = stderr.write(format!("Set-ItemProperty : {error}\n").as_bytes());
1104 ExitStatus::FAILURE
1105 }
1106 }
1107 }
1108
1109 fn builtin_remove_itemproperty(
1111 &self,
1112 argv: &[String],
1113 stdout: &mut dyn Output,
1114 stderr: &mut dyn Output,
1115 ) -> ExitStatus {
1116 let _ = stdout;
1117 let registry = match self.os.registry() {
1118 Ok(registry) => registry,
1119 Err(error) => {
1120 let _ = stderr.write(format!("Remove-ItemProperty : {error}\n").as_bytes());
1121 return ExitStatus::FAILURE;
1122 }
1123 };
1124 let path_arg = argv
1125 .iter()
1126 .skip(1)
1127 .find(|argument| !argument.starts_with('-'))
1128 .cloned()
1129 .unwrap_or_default();
1130 let (hive, path) = match Self::registry_path(&path_arg) {
1131 Some(parts) => parts,
1132 None => {
1133 let _ = stderr.write(
1134 format!(
1135 "Remove-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
1136 )
1137 .as_bytes(),
1138 );
1139 return ExitStatus::FAILURE;
1140 }
1141 };
1142 let mut name: Option<String> = None;
1143 let args: Vec<String> = argv.iter().skip(1).cloned().collect();
1144 let mut index = 0;
1145 while index < args.len() {
1146 if args[index].eq_ignore_ascii_case("-Name") {
1147 index += 1;
1148 name = args.get(index).cloned();
1149 }
1150 index += 1;
1151 }
1152 let Some(name) = name else {
1153 let _ = stderr.write(b"Remove-ItemProperty : Cannot bind argument to parameter 'Name' because it is an empty string.\n");
1154 return ExitStatus::FAILURE;
1155 };
1156 let actor = Some(self.actor);
1157 let key = match registry.key(actor, &hive, &path) {
1158 Ok(Some(key)) => key,
1159 _ => {
1160 let _ = stderr.write(
1161 format!(
1162 "Remove-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
1163 )
1164 .as_bytes(),
1165 );
1166 return ExitStatus::FAILURE;
1167 }
1168 };
1169 match registry.delete_value(actor, key, &name) {
1170 Ok(true) => ExitStatus::SUCCESS,
1171 Ok(false) => {
1172 let _ = stderr.write(
1173 format!(
1174 "Remove-ItemProperty : Cannot find path '{path_arg}\\{name}' because it does not exist.\n"
1175 )
1176 .as_bytes(),
1177 );
1178 ExitStatus::FAILURE
1179 }
1180 Err(error) => {
1181 let _ = stderr.write(format!("Remove-ItemProperty : {error}\n").as_bytes());
1182 ExitStatus::FAILURE
1183 }
1184 }
1185 }
1186
1187 fn registry_path(path: &str) -> Option<(String, String)> {
1189 let (hive, rest) = path.split_once(':')?;
1190 if !os::windows::registry::RegistryState::is_hive(hive) {
1191 return None;
1192 }
1193 Some((
1194 hive.to_owned(),
1195 rest.trim_start_matches('\\').replace('\\', "/"),
1196 ))
1197 }
1198
1199 fn builtin_get_alias(
1201 &self,
1202 argv: &[String],
1203 stdout: &mut dyn Output,
1204 stderr: &mut dyn Output,
1205 ) -> ExitStatus {
1206 if argv.len() > 1 {
1207 let mut exit_status = ExitStatus::SUCCESS;
1208 for name in argv.iter().skip(1) {
1209 let key = name.trim_start_matches('-').to_lowercase();
1210 if let Some(target) = self.aliases.get(&key) {
1211 let _ = stdout.write(format!("Alias {key} -> {target}\n").as_bytes());
1212 } else {
1213 let _ = stderr.write(
1214 format!(
1215 "Get-Alias: The term '{name}' is not recognized as the name of a cmdlet, function, script file, or operable program.\n"
1216 )
1217 .as_bytes(),
1218 );
1219 exit_status = ExitStatus::FAILURE;
1220 }
1221 }
1222 return exit_status;
1223 }
1224 for (name, target) in &self.aliases {
1225 let _ = stdout.write(format!("Alias {name} -> {target}\n").as_bytes());
1226 }
1227 ExitStatus::SUCCESS
1228 }
1229
1230 fn builtin_set_alias(
1232 &mut self,
1233 argv: &[String],
1234 stdout: &mut dyn Output,
1235 stderr: &mut dyn Output,
1236 ) -> ExitStatus {
1237 let _ = stdout;
1238 if argv.len() < 3 {
1239 let _ = stderr.write(b"Set-Alias: usage: Set-Alias [-Name] name [-Value] cmdlet\n");
1240 return ExitStatus::USAGE;
1241 }
1242 let mut name = None;
1243 let mut value = None;
1244 let mut index = 1;
1245 while index < argv.len() {
1246 match argv[index].as_str() {
1247 "-Name" => {
1248 name = argv.get(index + 1).cloned();
1249 index += 2;
1250 }
1251 "-Value" => {
1252 value = argv.get(index + 1).cloned();
1253 index += 2;
1254 }
1255 "-Scope" | "-Option" | "-Force" | "-PassThru" => {
1256 index += 1;
1257 if matches!(argv[index - 1].as_str(), "-Scope" | "-Option") {
1258 index += 1;
1259 }
1260 }
1261 argument if !argument.starts_with('-') && name.is_none() => {
1262 name = Some(argument.to_owned());
1263 index += 1;
1264 }
1265 argument if !argument.starts_with('-') && value.is_none() => {
1266 value = Some(argument.to_owned());
1267 index += 1;
1268 }
1269 _ => index += 1,
1270 }
1271 }
1272 let (Some(name), Some(value)) = (name, value) else {
1273 let _ = stderr.write(b"Set-Alias: usage: Set-Alias [-Name] name [-Value] cmdlet\n");
1274 return ExitStatus::USAGE;
1275 };
1276 self.aliases.insert(name.to_lowercase(), value);
1277 ExitStatus::SUCCESS
1278 }
1279
1280 fn builtin_history(&self, stdout: &mut dyn Output) -> ExitStatus {
1283 for (index, line) in self.history.iter().enumerate() {
1284 let _ = stdout.write(format!("{:5} {}\n", index + 1, line).as_bytes());
1285 }
1286 ExitStatus::SUCCESS
1287 }
1288
1289 fn builtin_get_localuser(
1292 &self,
1293 argv: &[String],
1294 stdout: &mut dyn Output,
1295 stderr: &mut dyn Output,
1296 ) -> ExitStatus {
1297 let users = self.os.users().users();
1298 let name_width = users
1299 .iter()
1300 .map(|user| user.name().len())
1301 .max()
1302 .unwrap_or(0)
1303 .max(4)
1304 + 1;
1305 let enabled_width = "Enabled".len() + 1;
1306 let header = format!(
1307 "{:<name_width$}{:<enabled_width$}Description\n",
1308 "Name", "Enabled"
1309 );
1310 let dashes = format!(
1311 "{:<name_width$}{:<enabled_width$}-----------\n",
1312 "----", "-------"
1313 );
1314 if let Some(target) = argv.get(1) {
1315 let Some(user) = users
1316 .iter()
1317 .find(|user| user.name().eq_ignore_ascii_case(target))
1318 else {
1319 let _ = stderr.write(
1320 format!("Get-LocalUser: Cannot find an object with identity: '{target}'.\n")
1321 .as_bytes(),
1322 );
1323 return ExitStatus::FAILURE;
1324 };
1325 let row = format!(
1326 "{:<name_width$}{:<enabled_width$}\n",
1327 user.name(),
1328 if user.enabled() { "True" } else { "False" }
1329 );
1330 let _ = stdout.write(header.as_bytes());
1331 let _ = stdout.write(dashes.as_bytes());
1332 let _ = stdout.write(row.as_bytes());
1333 return ExitStatus::SUCCESS;
1334 }
1335 let _ = stdout.write(header.as_bytes());
1336 let _ = stdout.write(dashes.as_bytes());
1337 for user in users {
1338 let row = format!(
1339 "{:<name_width$}{:<enabled_width$}\n",
1340 user.name(),
1341 if user.enabled() { "True" } else { "False" }
1342 );
1343 let _ = stdout.write(row.as_bytes());
1344 }
1345 ExitStatus::SUCCESS
1346 }
1347
1348 fn builtin_get_localgroup(
1350 &self,
1351 argv: &[String],
1352 stdout: &mut dyn Output,
1353 stderr: &mut dyn Output,
1354 ) -> ExitStatus {
1355 let groups = self.os.groups();
1356 let name_width = groups
1357 .iter()
1358 .map(|group| group.name.len())
1359 .max()
1360 .unwrap_or(0)
1361 .max(4)
1362 + 1;
1363 let header = format!("{:<name_width$}Description\n", "Name");
1364 let dashes = format!("{:<name_width$}-----------\n", "----");
1365 if let Some(target) = argv.get(1) {
1366 let Some(group) = groups
1367 .iter()
1368 .find(|group| group.name.eq_ignore_ascii_case(target))
1369 else {
1370 let _ = stderr.write(
1371 format!("Get-LocalGroup: Cannot find an object with identity: '{target}'.\n")
1372 .as_bytes(),
1373 );
1374 return ExitStatus::FAILURE;
1375 };
1376 let _ = stdout.write(header.as_bytes());
1377 let _ = stdout.write(dashes.as_bytes());
1378 let _ = stdout.write(format!("{:<name_width$}\n", group.name).as_bytes());
1379 return ExitStatus::SUCCESS;
1380 }
1381 let _ = stdout.write(header.as_bytes());
1382 let _ = stdout.write(dashes.as_bytes());
1383 for group in groups {
1384 let _ = stdout.write(format!("{:<name_width$}\n", group.name).as_bytes());
1385 }
1386 ExitStatus::SUCCESS
1387 }
1388
1389 fn builtin_get_service(
1391 &self,
1392 argv: &[String],
1393 stdout: &mut dyn Output,
1394 stderr: &mut dyn Output,
1395 ) -> ExitStatus {
1396 let services = match self.os.service_state() {
1397 Ok(services) => services,
1398 Err(error) => {
1399 let _ = stderr.write(format!("Get-Service : {error}\n").as_bytes());
1400 return ExitStatus::FAILURE;
1401 }
1402 };
1403 if let Some(target) = argv.get(1) {
1404 let Some(object) = services.find(target).unwrap_or(None) else {
1405 let _ = stderr.write(
1406 format!(
1407 "Get-Service : Cannot find any service with service name '{target}'.\n"
1408 )
1409 .as_bytes(),
1410 );
1411 return ExitStatus::FAILURE;
1412 };
1413 let (name, state) = services
1414 .entries()
1415 .unwrap_or_default()
1416 .into_iter()
1417 .find(|(_, entry_object)| *entry_object == object)
1418 .map(|(name, _)| (name, services.state(object)))
1419 .unwrap_or_else(|| (target.to_owned(), services.state(object)));
1420 let _ = stdout.write(
1421 format!(
1422 "Status Name DisplayName\n------ ---- -----------\n{:<7} {:<18} {}\n",
1423 state, name, name
1424 )
1425 .as_bytes(),
1426 );
1427 return ExitStatus::SUCCESS;
1428 }
1429 let _ = stdout.write(
1430 b"Status Name DisplayName\n------ ---- -----------\n",
1431 );
1432 for (entry, object) in services.entries().unwrap_or_default() {
1433 let state = services.state(object);
1434 let _ = stdout.write(format!("{:<7} {:<18} {}\n", state, entry, entry).as_bytes());
1435 }
1436 ExitStatus::SUCCESS
1437 }
1438
1439 fn builtin_get_item(
1441 &self,
1442 argv: &[String],
1443 stdout: &mut dyn Output,
1444 stderr: &mut dyn Output,
1445 ) -> ExitStatus {
1446 let Some(target) = argv.get(1) else {
1447 let _ = stderr.write(b"Get-Item: missing path\n");
1448 return ExitStatus::USAGE;
1449 };
1450 let path = match self.resolve_path(target) {
1451 Ok(path) => path,
1452 Err(_) => {
1453 let _ = stderr.write(
1454 format!(
1455 "Get-Item: Cannot find path '{}' because it does not exist.\n",
1456 self.display_path_of(target)
1457 )
1458 .as_bytes(),
1459 );
1460 return ExitStatus::FAILURE;
1461 }
1462 };
1463 match self.os.engine().lookup(Some(self.actor), &path) {
1464 Ok(object) => {
1465 let name = path.name().map(str::to_owned).unwrap_or_default();
1466 let directory = self.os.engine().list(Some(self.actor), object).is_ok();
1467 let kind = if directory { "Directory" } else { "File" };
1468 let parent = path.parent().unwrap_or_else(|| path.clone());
1469 let _ = stdout.write(
1470 format!(
1471 " Directory: {}\n\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n{kind} {name}\n",
1472 self.display_path(&parent)
1473 )
1474 .as_bytes(),
1475 );
1476 }
1477 Err(_) => {
1478 let _ = stderr.write(
1479 format!(
1480 "Get-Item: Cannot find path '{}' because it does not exist.\n",
1481 self.display_path_of(target)
1482 )
1483 .as_bytes(),
1484 );
1485 return ExitStatus::FAILURE;
1486 }
1487 }
1488 ExitStatus::SUCCESS
1489 }
1490
1491 fn builtin_remove_item(
1493 &self,
1494 argv: &[String],
1495 stdout: &mut dyn Output,
1496 stderr: &mut dyn Output,
1497 ) -> ExitStatus {
1498 let _ = stdout;
1499 let mut recursive = false;
1500 let mut targets: Vec<&String> = Vec::new();
1501 for argument in argv.iter().skip(1) {
1502 if argument == "-Recurse" || argument == "-r" {
1503 recursive = true;
1504 } else if argument.starts_with('-') {
1505 continue;
1506 } else {
1507 targets.push(argument);
1508 }
1509 }
1510 let mut exit_status = ExitStatus::SUCCESS;
1511 for target in targets {
1512 let path = match self.resolve_path(target) {
1513 Ok(path) => path,
1514 Err(_) => {
1515 let _ = stderr.write(
1516 format!(
1517 "Remove-Item: Cannot find path '{}' because it does not exist.\n",
1518 self.display_path_of(target)
1519 )
1520 .as_bytes(),
1521 );
1522 exit_status = ExitStatus::FAILURE;
1523 continue;
1524 }
1525 };
1526 match self.os.engine().lookup(Some(self.actor), &path) {
1527 Ok(object) => {
1528 let is_directory = self.os.engine().list(Some(self.actor), object).is_ok();
1529 if is_directory && !recursive {
1530 let _ = stderr.write(
1531 format!(
1532 "Remove-Item: Cannot remove item '{}': access to the path is denied.\n",
1533 self.display_path(&path)
1534 )
1535 .as_bytes(),
1536 );
1537 exit_status = ExitStatus::FAILURE;
1538 continue;
1539 }
1540 if self.os.engine().delete(Some(self.actor), object).is_err() {
1541 exit_status = ExitStatus::FAILURE;
1542 }
1543 }
1544 Err(_) => {
1545 let _ = stderr.write(
1546 format!(
1547 "Remove-Item: Cannot find path '{}' because it does not exist.\n",
1548 self.display_path_of(target)
1549 )
1550 .as_bytes(),
1551 );
1552 exit_status = ExitStatus::FAILURE;
1553 }
1554 }
1555 }
1556 exit_status
1557 }
1558
1559 fn builtin_cd(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
1560 let Some(target) = argv.get(1) else {
1561 return ExitStatus::SUCCESS;
1562 };
1563 let path = match self.resolve_path(target) {
1564 Ok(path) => path,
1565 Err(_) => {
1566 let _ = stderr.write(
1567 format!(
1568 "cd: Cannot find path '{}' because it does not exist.\n",
1569 self.display_path_of(target)
1570 )
1571 .as_bytes(),
1572 );
1573 return ExitStatus::FAILURE;
1574 }
1575 };
1576 let exists = self
1577 .os
1578 .engine()
1579 .lookup(Some(self.actor), &path)
1580 .is_ok_and(|object| self.os.engine().children(Some(self.actor), object).is_ok());
1581 if !exists {
1582 let _ = stderr.write(
1583 format!(
1584 "cd: Cannot find path '{}' because it does not exist.\n",
1585 self.display_path_of(target)
1586 )
1587 .as_bytes(),
1588 );
1589 return ExitStatus::FAILURE;
1590 }
1591 self.cwd = path;
1592 ExitStatus::SUCCESS
1593 }
1594
1595 fn builtin_pwd(&self, stdout: &mut dyn Output) -> ExitStatus {
1596 let _ = stdout.write(format!("{}\n", self.display_path(&self.cwd)).as_bytes());
1597 ExitStatus::SUCCESS
1598 }
1599
1600 fn builtin_echo(&self, argv: &[String], stdout: &mut dyn Output) -> ExitStatus {
1601 let text = argv[1..].join(" ");
1602 let _ = stdout.write(format!("{text}\n").as_bytes());
1603 ExitStatus::SUCCESS
1604 }
1605
1606 fn builtin_cat(
1607 &self,
1608 argv: &[String],
1609 stdout: &mut dyn Output,
1610 stderr: &mut dyn Output,
1611 ) -> ExitStatus {
1612 if argv.len() < 2 {
1613 let _ = stderr.write(b"Get-Content: missing path\n");
1614 return ExitStatus::USAGE;
1615 }
1616 let mut exit_status = ExitStatus::SUCCESS;
1617 for path_str in argv.iter().skip(1) {
1618 let path = match self.resolve_path(path_str) {
1619 Ok(path) => path,
1620 Err(_) => {
1621 let _ = stderr.write(
1622 format!(
1623 "Get-Content: Cannot find path '{path_str}' because it does not exist.\n"
1624 )
1625 .as_bytes(),
1626 );
1627 exit_status = ExitStatus::FAILURE;
1628 continue;
1629 }
1630 };
1631 let content = self
1632 .os
1633 .engine()
1634 .lookup(Some(self.actor), &path)
1635 .ok()
1636 .and_then(|object| {
1637 self.os
1638 .engine()
1639 .read(Some(self.actor), object)
1640 .ok()
1641 .flatten()
1642 });
1643 match content {
1644 Some(bytes) => {
1645 let _ = stdout.write(&bytes);
1646 }
1647 None => {
1648 let _ = stderr.write(
1649 format!(
1650 "Get-Content: Cannot find path '{path_str}' because it does not exist.\n"
1651 )
1652 .as_bytes(),
1653 );
1654 exit_status = ExitStatus::FAILURE;
1655 }
1656 }
1657 }
1658 exit_status
1659 }
1660
1661 fn builtin_ls(
1662 &self,
1663 argv: &[String],
1664 stdout: &mut dyn Output,
1665 stderr: &mut dyn Output,
1666 ) -> ExitStatus {
1667 let target = argv.get(1).cloned().unwrap_or_else(|| self.cwd.to_string());
1668 let path = match self.resolve_path(&target) {
1669 Ok(path) => path,
1670 Err(_) => {
1671 let _ = stderr.write(
1672 format!(
1673 "ls: Cannot find path '{}' because it does not exist.\n",
1674 self.display_path_of(&target)
1675 )
1676 .as_bytes(),
1677 );
1678 return ExitStatus::FAILURE;
1679 }
1680 };
1681 let directory = match self.os.engine().lookup(Some(self.actor), &path) {
1682 Ok(object) => object,
1683 Err(_) => {
1684 let _ = stderr.write(
1685 format!(
1686 "ls: Cannot find path '{}' because it does not exist.\n",
1687 self.display_path_of(&target)
1688 )
1689 .as_bytes(),
1690 );
1691 return ExitStatus::FAILURE;
1692 }
1693 };
1694 let Ok(entries) = self.os.engine().list(Some(self.actor), directory) else {
1695 let name = path.name().unwrap_or(&target).to_owned();
1697 let _ = stdout.write(format!("{name}\n").as_bytes());
1698 return ExitStatus::SUCCESS;
1699 };
1700 for (name, _) in entries {
1701 let _ = stdout.write(format!("{}\n", name.as_str()).as_bytes());
1702 }
1703 ExitStatus::SUCCESS
1704 }
1705}
1706
1707impl<'os> crate::Shell for PowerShell<'os> {
1708 fn name(&self) -> &'static str {
1709 "powershell"
1710 }
1711
1712 fn actor(&self) -> engine::ActorId {
1713 self.actor
1714 }
1715
1716 fn environment(&self) -> &os::Environment {
1717 &self.environment
1718 }
1719
1720 fn engine(&self) -> &Engine {
1721 self.os.engine()
1722 }
1723
1724 fn boot_time(&self) -> engine::Timestamp {
1725 self.os.boot_time()
1726 }
1727
1728 fn hostname(&self) -> String {
1729 self.environment
1730 .get("COMPUTERNAME")
1731 .unwrap_or("vce")
1732 .to_owned()
1733 }
1734
1735 fn cwd(&self) -> &VirtualPath {
1736 &self.cwd
1737 }
1738
1739 fn banner(&self) -> Option<String> {
1740 Some(
1743 "Windows PowerShell\nCopyright (C) Microsoft Corporation. All rights reserved.\n"
1744 .to_owned(),
1745 )
1746 }
1747
1748 fn prompt(&self, hostname: &str) -> String {
1749 let _ = hostname;
1750 format!("PS {}> ", self.display_path(&self.cwd))
1751 }
1752
1753 fn set_terminal_size(&mut self, rows: u16, cols: u16) {
1754 self.environment.set("COLUMNS", cols.to_string());
1755 self.environment.set("LINES", rows.to_string());
1756 }
1757
1758 fn execute(
1759 &mut self,
1760 line: &str,
1761 stdin: &mut dyn Input,
1762 stdout: &mut dyn Output,
1763 stderr: &mut dyn Output,
1764 ) -> ExitStatus {
1765 self.run_line(line, stdin, stdout, stderr)
1766 }
1767
1768 fn execute_with_terminal(
1769 &mut self,
1770 line: &str,
1771 stdin: &mut dyn Input,
1772 stdout: &mut dyn Output,
1773 stderr: &mut dyn Output,
1774 _terminal: Option<&mut dyn Terminal>,
1775 ) -> ExitStatus {
1776 self.run_line(line, stdin, stdout, stderr)
1777 }
1778
1779 fn take_exit_status(&mut self) -> Option<ExitStatus> {
1780 self.exit_request.take()
1781 }
1782
1783 fn history(&self) -> &[String] {
1784 &self.history
1785 }
1786
1787 fn record_history(&mut self, line: &str) {
1788 if line.trim().is_empty() {
1789 return;
1790 }
1791 self.history.push(line.to_owned());
1792 if self.history.len() > crate::HISTORY_LIMIT {
1793 self.history.remove(0);
1794 }
1795 }
1796}
1797
1798fn word_text(token: &Token, source: &str, environment: &Environment) -> Option<String> {
1801 let text = token.text(source);
1802 match token.kind {
1803 TokenKind::Whitespace
1804 | TokenKind::Newline
1805 | TokenKind::LineComment
1806 | TokenKind::BlockComment
1807 | TokenKind::Semicolon
1808 | TokenKind::Pipe
1809 | TokenKind::LCurly
1810 | TokenKind::RCurly
1811 | TokenKind::LParen
1812 | TokenKind::RParen
1813 | TokenKind::Comma => None,
1814 TokenKind::StringLiteral => Some(unquote(text)),
1815 TokenKind::StringExpandable => Some(expand_string(text, environment)),
1816 TokenKind::Variable => {
1817 let name = text.trim_start_matches('$');
1818 Some(environment.get(name).unwrap_or("").to_owned())
1819 }
1820 TokenKind::Operator(_) if is_redirect(token, source) => None,
1821 _ => Some(text.to_owned()),
1822 }
1823}
1824
1825fn is_redirect(token: &Token, source: &str) -> bool {
1827 let text = token.text(source);
1828 matches!(text, ">" | ">>" | "<")
1829}
1830
1831fn unquote(text: &str) -> String {
1833 if let Some(inner) = text
1834 .strip_prefix('\'')
1835 .and_then(|value| value.strip_suffix('\''))
1836 {
1837 inner.replace("''", "'")
1838 } else if let Some(inner) = text
1839 .strip_prefix('"')
1840 .and_then(|value| value.strip_suffix('"'))
1841 {
1842 inner.to_owned()
1843 } else {
1844 text.to_owned()
1845 }
1846}
1847
1848fn expand_string(text: &str, environment: &Environment) -> String {
1850 let mut result = String::new();
1851 let mut chars = text.trim_matches('"').chars().peekable();
1852 while let Some(ch) = chars.next() {
1853 if ch == '$' {
1854 let mut name = String::new();
1855 while let Some(&next) = chars.peek() {
1856 if next.is_alphanumeric() || next == '_' {
1857 name.push(next);
1858 chars.next();
1859 } else {
1860 break;
1861 }
1862 }
1863 result.push_str(environment.get(&name).unwrap_or(""));
1864 } else {
1865 result.push(ch);
1866 }
1867 }
1868 result
1869}
1870
1871fn read_file(shell: &PowerShell<'_>, path: &str) -> BytesInput {
1873 let engine = shell.os.engine();
1874 let actor = Some(shell.actor);
1875 let Ok(path) = shell.resolve_path(path) else {
1876 return BytesInput::new(Vec::new());
1877 };
1878 let content = engine
1879 .lookup(actor, &path)
1880 .ok()
1881 .and_then(|object| engine.read(actor, object).ok().flatten())
1882 .unwrap_or_default();
1883 BytesInput::new(content)
1884}
1885
1886fn split_statements(tokens: &[Token]) -> Vec<Vec<Token>> {
1888 let mut statements = Vec::new();
1889 let mut current = Vec::new();
1890 for token in tokens {
1891 if matches!(token.kind, TokenKind::Semicolon | TokenKind::Newline) {
1892 if !current.is_empty() {
1893 statements.push(std::mem::take(&mut current));
1894 }
1895 } else {
1896 current.push(*token);
1897 }
1898 }
1899 if !current.is_empty() {
1900 statements.push(current);
1901 }
1902 statements
1903}
1904
1905fn split_pipeline(tokens: &[Token]) -> Vec<Vec<Token>> {
1907 let mut stages = Vec::new();
1908 let mut current = Vec::new();
1909 for token in tokens {
1910 if token.kind == TokenKind::Pipe {
1911 if !current.is_empty() {
1912 stages.push(std::mem::take(&mut current));
1913 }
1914 } else {
1915 current.push(*token);
1916 }
1917 }
1918 if !current.is_empty() {
1919 stages.push(current);
1920 }
1921 stages
1922}
1923
1924fn parent_of_display(display: &str) -> String {
1929 match display.rfind('\\') {
1930 Some(index) => display[..index].to_owned(),
1931 None => String::new(),
1932 }
1933}
1934
1935fn default_aliases() -> [(&'static str, &'static str); 37] {
1938 [
1939 ("cat", "Get-Content"),
1940 ("cd", "Set-Location"),
1941 ("chdir", "Set-Location"),
1942 ("clear", "Clear-Host"),
1943 ("cls", "Clear-Host"),
1944 ("copy", "Copy-Item"),
1945 ("cp", "Copy-Item"),
1946 ("del", "Remove-Item"),
1947 ("dir", "Get-ChildItem"),
1948 ("echo", "Write-Output"),
1949 ("gc", "Get-Content"),
1950 ("gci", "Get-ChildItem"),
1951 ("gi", "Get-Item"),
1952 ("gl", "Get-Location"),
1953 ("h", "Get-History"),
1954 ("history", "Get-History"),
1955 ("ls", "Get-ChildItem"),
1956 ("gps", "Get-Process"),
1957 ("kill", "Stop-Process"),
1958 ("mi", "Move-Item"),
1959 ("mv", "Move-Item"),
1960 ("ni", "New-Item"),
1961 ("ps", "Get-Process"),
1962 ("pwd", "Get-Location"),
1963 ("gp", "Get-ItemProperty"),
1964 ("sp", "Set-ItemProperty"),
1965 ("rp", "Remove-ItemProperty"),
1966 ("rd", "Remove-Item"),
1967 ("rm", "Remove-Item"),
1968 ("rmdir", "Remove-Item"),
1969 ("sal", "Set-Alias"),
1970 ("sc", "Set-Content"),
1971 ("sleep", "Start-Sleep"),
1972 ("sl", "Set-Location"),
1973 ("gd", "Get-Date"),
1974 ("type", "Get-Content"),
1975 ("write", "Write-Output"),
1976 ]
1977}
1978
1979#[cfg(test)]
1980mod tests {
1981 use super::*;
1982 use crate::Shell;
1983 use engine::Timestamp;
1984 use os::HostIdentity;
1985 use os::windows::Windows;
1986
1987 fn session() -> (Box<PowerShell<'static>>, &'static Windows) {
1988 let windows = Box::leak(Box::new(
1989 Windows::with_identity(
1990 &HostIdentity::new("demo", "demo-host"),
1991 Timestamp::from_nanos(1_000_000),
1992 )
1993 .unwrap(),
1994 ));
1995 let actor = windows.authenticate("demo", "demo").unwrap();
1996 let shell =
1997 Box::new(PowerShell::new(windows, actor, windows.environment().clone()).unwrap());
1998 (shell, windows)
1999 }
2000
2001 #[test]
2002 fn powershell_runs_builtins_and_prompt() {
2003 let (mut shell, _windows) = session();
2004 assert_eq!(shell.prompt("demo-host"), "PS C:\\Users\\demo> ");
2005 let mut stdout = BytesOutput::new();
2006 let mut stderr = BytesOutput::new();
2007 shell.execute(
2008 "echo hello",
2009 &mut BytesInput::new(b""),
2010 &mut stdout,
2011 &mut stderr,
2012 );
2013 assert_eq!(stdout.bytes(), b"hello\n");
2014 shell.execute("pwd", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
2015 assert!(String::from_utf8_lossy(stdout.bytes()).contains("C:\\Users\\demo"));
2016 }
2017
2018 #[test]
2019 fn powershell_lists_the_profile() {
2020 let (mut shell, _windows) = session();
2021 let mut stdout = BytesOutput::new();
2022 let mut stderr = BytesOutput::new();
2023 shell.execute("ls", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
2024 let text = String::from_utf8(stdout.into_bytes()).unwrap();
2025 assert!(text.contains("Desktop"), "profile folders: {text}");
2026 assert!(text.contains("Documents"));
2027 }
2028
2029 #[test]
2030 fn powershell_reports_missing_commands() {
2031 let (mut shell, _windows) = session();
2032 let mut stdout = BytesOutput::new();
2033 let mut stderr = BytesOutput::new();
2034 let status = shell.execute(
2035 "not-a-command",
2036 &mut BytesInput::new(b""),
2037 &mut stdout,
2038 &mut stderr,
2039 );
2040 assert_eq!(status, ExitStatus::NOT_FOUND);
2041 assert!(String::from_utf8_lossy(stderr.bytes()).contains("not recognized"));
2042 }
2043
2044 #[test]
2045 fn powershell_aliases_resolve_to_cmdlets() {
2046 let (mut shell, _windows) = session();
2047 let mut stdout = BytesOutput::new();
2048 let mut stderr = BytesOutput::new();
2049 shell.execute(
2050 "echo hello > t.txt",
2051 &mut BytesInput::new(b""),
2052 &mut stdout,
2053 &mut stderr,
2054 );
2055 let status = shell.execute(
2057 "cat t.txt",
2058 &mut BytesInput::new(b""),
2059 &mut stdout,
2060 &mut stderr,
2061 );
2062 assert_eq!(status, ExitStatus::SUCCESS);
2063 assert_eq!(stdout.bytes(), b"hello\n");
2064 let mut alias_out = BytesOutput::new();
2066 shell.execute(
2067 "Get-Alias cat",
2068 &mut BytesInput::new(b""),
2069 &mut alias_out,
2070 &mut stderr,
2071 );
2072 assert_eq!(
2073 String::from_utf8_lossy(alias_out.bytes()),
2074 "Alias cat -> Get-Content\n"
2075 );
2076 }
2077
2078 #[test]
2079 fn set_content_preserves_dash_prefixed_values() {
2080 let (mut shell, _windows) = session();
2081 let mut stdout = BytesOutput::new();
2082 let mut stderr = BytesOutput::new();
2083 let status = shell.execute(
2084 "Set-Content -Path Desktop\\work-order.txt -Value '- first item' '--------' 'company''s policy'",
2085 &mut BytesInput::new(b""),
2086 &mut stdout,
2087 &mut stderr,
2088 );
2089 assert_eq!(
2090 status,
2091 ExitStatus::SUCCESS,
2092 "{}",
2093 String::from_utf8_lossy(stderr.bytes())
2094 );
2095
2096 let mut contents = BytesOutput::new();
2097 let status = shell.execute(
2098 "Get-Content Desktop\\work-order.txt",
2099 &mut BytesInput::new(b""),
2100 &mut contents,
2101 &mut stderr,
2102 );
2103 assert_eq!(status, ExitStatus::SUCCESS);
2104 assert_eq!(
2105 contents.bytes(),
2106 b"- first item\n--------\ncompany's policy\n"
2107 );
2108 }
2109
2110 #[test]
2111 fn powershell_cd_and_variables() {
2112 let (mut shell, _windows) = session();
2113 let mut stdout = BytesOutput::new();
2114 let mut stderr = BytesOutput::new();
2115 shell.execute(
2116 "cd C:\\Windows\\System32",
2117 &mut BytesInput::new(b""),
2118 &mut stdout,
2119 &mut stderr,
2120 );
2121 assert_eq!(shell.cwd().to_string(), "/Windows/System32");
2122 shell.execute("pwd", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
2123 assert!(String::from_utf8_lossy(stdout.bytes()).contains("C:\\Windows\\System32"));
2124 let status = shell.execute(
2126 "cd C:/Users/demo/Desktop/",
2127 &mut BytesInput::new(b""),
2128 &mut stdout,
2129 &mut stderr,
2130 );
2131 assert_eq!(status, ExitStatus::SUCCESS);
2132 assert_eq!(shell.cwd().to_string(), "/Users/demo/Desktop");
2133 }
2134
2135 #[test]
2136 fn cd_backslash_goes_to_root() {
2137 let (mut shell, _) = session();
2138 let mut stdout = BytesOutput::new();
2139 let mut stderr = BytesOutput::new();
2140 shell.execute(
2141 "cd C:\\Windows",
2142 &mut BytesInput::new(b""),
2143 &mut stdout,
2144 &mut stderr,
2145 );
2146 assert_eq!(shell.cwd().to_string(), "/Windows");
2147 stdout = BytesOutput::new();
2148 stderr = BytesOutput::new();
2149 let status = shell.execute("cd \\", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
2150 assert_eq!(status, os::runtime::ExitStatus::SUCCESS);
2151 assert_eq!(shell.cwd().to_string(), "/");
2152 shell.execute(
2153 "cd C:\\Windows",
2154 &mut BytesInput::new(b""),
2155 &mut stdout,
2156 &mut stderr,
2157 );
2158 stdout = BytesOutput::new();
2159 stderr = BytesOutput::new();
2160 let status = shell.execute("cd\\", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
2161 assert_eq!(status, os::runtime::ExitStatus::SUCCESS);
2162 assert_eq!(shell.cwd().to_string(), "/");
2163 }
2164
2165 #[test]
2166 fn needs_continuation_for_powershell_is_false_for_cd_backslash() {
2167 let (shell, _) = session();
2168 assert!(!shell.needs_continuation("cd \\\n"));
2169 assert!(!shell.needs_continuation("cd C:\\Windows\n"));
2170 }
2171}