use engine::{BytesInput, BytesOutput, Engine, Input, Output, Pipe, Terminal, VirtualPath};
use os::runtime::ExitStatus;
use os::windows::Windows;
use os::{Environment, OperatingSystem};
use pwsh_parser::{Token, TokenKind};
pub struct PowerShell<'os> {
os: &'os Windows,
actor: engine::ActorId,
cwd: VirtualPath,
environment: Environment,
aliases: std::collections::BTreeMap<String, String>,
exit_request: Option<ExitStatus>,
history: Vec<String>,
}
impl<'os> PowerShell<'os> {
pub fn new(
os: &'os Windows,
actor: engine::ActorId,
environment: Environment,
) -> Result<Self, os::OsError> {
let user_name = os
.users()
.get(actor.get() as u32)
.map(|user| user.name().to_owned())
.unwrap_or_else(|| "Administrator".to_owned());
let home: VirtualPath = format!("/Users/{user_name}").parse().expect("valid path");
let cwd = if os.engine().lookup(Some(actor), &home).is_ok() {
home
} else {
VirtualPath::root()
};
let aliases: std::collections::BTreeMap<String, String> = default_aliases()
.into_iter()
.map(|(name, target)| (name.to_owned(), target.to_owned()))
.collect();
Ok(Self {
os,
actor,
cwd,
environment,
aliases,
exit_request: None,
history: Vec::new(),
})
}
pub fn actor(&self) -> engine::ActorId {
self.actor
}
pub fn environment(&self) -> &Environment {
&self.environment
}
fn run_line(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let lexed = pwsh_parser::tokenize(line);
let mut last_status = ExitStatus::SUCCESS;
for statement in split_statements(&lexed.tokens) {
last_status = self.run_pipeline(&statement, line, stdin, stdout, stderr);
}
last_status
}
fn run_pipeline(
&mut self,
tokens: &[Token],
source: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let stages = split_pipeline(tokens);
if stages.len() == 1 {
return self.run_stage(&stages[0], source, stdin, stdout, stderr);
}
let pipes: Vec<Pipe> = (0..stages.len() - 1).map(|_| Pipe::new()).collect();
let mut last_status = ExitStatus::SUCCESS;
for (index, stage) in stages.iter().enumerate() {
let is_last = index == stages.len() - 1;
if is_last {
let mut pipe_in = pipes[index - 1].input();
last_status = self.run_stage(stage, source, &mut pipe_in, stdout, stderr);
} else {
let mut pipe_out = pipes[index].output();
let pipe_in = if index == 0 {
&mut *stdin
} else {
&mut pipes[index - 1].input()
};
last_status = self.run_stage(stage, source, pipe_in, &mut pipe_out, stderr);
}
}
last_status
}
fn run_stage(
&mut self,
tokens: &[Token],
source: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let mut argv = Vec::new();
let mut stdin_source: Option<BytesInput> = None;
let mut captured = BytesOutput::new();
let mut stdout_redirect: Option<(String, bool)> = None;
let mut string_expression = false;
let mut first_word_seen = false;
let mut index = 0;
while index < tokens.len() {
let token = &tokens[index];
if !first_word_seen
&& matches!(
token.kind,
TokenKind::StringLiteral | TokenKind::StringExpandable
)
{
string_expression = true;
}
match token.kind {
TokenKind::Operator(_) if is_redirect(token, source) => {
let operator = token.text(source);
index += 1;
while index < tokens.len()
&& matches!(
tokens[index].kind,
TokenKind::Whitespace | TokenKind::Newline
)
{
index += 1;
}
let target = tokens
.get(index)
.map(|t| word_text(t, source, &self.environment).unwrap_or_default())
.unwrap_or_default();
if operator == "<" {
stdin_source = Some(read_file(self, &target));
} else {
stdout_redirect = Some((target, operator == ">>"));
}
}
_ => {
if let Some(word) = word_text(token, source, &self.environment) {
argv.push(word);
first_word_seen = true;
}
}
}
index += 1;
}
if argv.is_empty() {
return ExitStatus::SUCCESS;
}
if string_expression {
let value = argv.join(" ");
if let Some((path, append)) = stdout_redirect {
if let Err(error) =
self.write_redirect(&path, format!("{value}\n").as_bytes(), append)
{
let _ = stderr.write(format!("{error}\n").as_bytes());
return ExitStatus::FAILURE;
}
} else {
let _ = stdout.write(format!("{value}\n").as_bytes());
}
return ExitStatus::SUCCESS;
}
let argv = {
let mut normalized_argv = argv;
if normalized_argv.len() == 1 {
let first = normalized_argv[0].clone();
let lower = first.to_lowercase();
for prefix in ["cd", "chdir", "sl"] {
if lower.starts_with(prefix) && lower.len() > prefix.len() {
let rest = first[prefix.len()..].to_owned();
if rest.starts_with('\\')
|| rest.starts_with('/')
|| rest.starts_with('.')
|| rest.starts_with(':')
{
normalized_argv = vec![prefix.to_string(), rest];
break;
}
}
}
}
normalized_argv
};
let command = argv[0].clone();
let resolved = self
.aliases
.get(&command.to_lowercase())
.cloned()
.unwrap_or_else(|| command.clone());
let effective_stdin: &mut dyn Input = match &mut stdin_source {
Some(input) => input,
None => stdin,
};
let effective_stdout: &mut dyn Output = if stdout_redirect.is_some() {
&mut captured
} else {
stdout
};
if let Some(status) =
self.try_builtin(&resolved, &argv, effective_stdin, effective_stdout, stderr)
{
if let Some((path, append)) = stdout_redirect
&& let Err(error) = self.write_redirect(&path, &captured.into_bytes(), append)
{
let _ = stderr.write(format!("{command}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
return status;
}
let status = match crate::windows_core::run_external(
self.os,
self.actor,
&self.cwd,
&self.environment,
&command,
&argv,
effective_stdin,
effective_stdout,
stderr,
) {
Some(status) => status,
None => {
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());
ExitStatus::NOT_FOUND
}
};
if let Some((path, append)) = stdout_redirect
&& let Err(error) = self.write_redirect(&path, &captured.into_bytes(), append)
{
let _ = stderr.write(format!("{command}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
status
}
fn write_redirect(
&self,
path_str: &str,
bytes: &[u8],
append: bool,
) -> Result<(), os::OsError> {
crate::windows_core::write_redirect(self.os, self.actor, &self.cwd, path_str, bytes, append)
}
fn resolve_path(&self, argument: &str) -> Result<VirtualPath, os::OsError> {
crate::windows_core::resolve_path(&self.cwd, argument)
}
fn display_path(&self, path: &engine::VirtualPath) -> String {
crate::windows_core::display_path(path)
}
fn display_path_of(&self, argument: &str) -> String {
match self.resolve_path(argument) {
Ok(path) => self.display_path(&path),
Err(_) => argument.to_owned(),
}
}
fn try_builtin(
&mut self,
name: &str,
argv: &[String],
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> Option<ExitStatus> {
let _ = stdin;
match name.to_lowercase().as_str() {
"set-location" => Some(self.builtin_cd(argv, stderr)),
"get-location" => Some(self.builtin_pwd(stdout)),
"get-childitem" => Some(self.builtin_ls(argv, stdout, stderr)),
"get-content" => Some(self.builtin_cat(argv, stdout, stderr)),
"write-output" => Some(self.builtin_echo(argv, stdout)),
"clear-host" => Some(self.builtin_clear_host(stdout)),
"get-alias" => Some(self.builtin_get_alias(argv, stdout, stderr)),
"set-alias" => Some(self.builtin_set_alias(argv, stdout, stderr)),
"get-history" => Some(self.builtin_history(stdout)),
"get-localuser" => Some(self.builtin_get_localuser(argv, stdout, stderr)),
"get-localgroup" => Some(self.builtin_get_localgroup(argv, stdout, stderr)),
"get-service" => Some(self.builtin_get_service(argv, stdout, stderr)),
"get-item" => Some(self.builtin_get_item(argv, stdout, stderr)),
"remove-item" => Some(self.builtin_remove_item(argv, stdout, stderr)),
"set-content" => Some(self.builtin_set_content(argv, stdout, stderr)),
"copy-item" => Some(self.builtin_copy_item(argv, stdout, stderr)),
"move-item" => Some(self.builtin_move_item(argv, stdout, stderr)),
"new-item" => Some(self.builtin_new_item(argv, stdout, stderr)),
"get-process" => Some(self.builtin_get_process(argv, stdout, stderr)),
"stop-process" => Some(self.builtin_stop_process(argv, stdout, stderr)),
"get-itemproperty" => Some(self.builtin_get_itemproperty(argv, stdout, stderr)),
"set-itemproperty" => Some(self.builtin_set_itemproperty(argv, stdout, stderr)),
"remove-itemproperty" => Some(self.builtin_remove_itemproperty(argv, stdout, stderr)),
"start-sleep" => Some(self.builtin_start_sleep(argv, stderr)),
"get-date" => Some(self.builtin_get_date(stdout)),
"exit" => {
let code = argv
.get(1)
.and_then(|value| value.trim().parse::<i64>().ok())
.map_or(0, |value| u8::try_from(value & 0xFF).unwrap_or(0));
let status = ExitStatus::new(code);
self.exit_request = Some(status);
Some(status)
}
_ => None,
}
}
fn builtin_set_content(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let mut path: Option<String> = None;
let mut values: Vec<String> = Vec::new();
let mut append = false;
let mut positional_value = false;
for argument in argv.iter().skip(1) {
if argument.eq_ignore_ascii_case("-Path") {
positional_value = false;
} else if argument.eq_ignore_ascii_case("-Value") {
positional_value = true;
} else if argument.eq_ignore_ascii_case("-Append") {
append = true;
} else if argument.starts_with('-') && !positional_value {
continue;
} else if path.is_none() && !positional_value {
path = Some(argument.clone());
} else {
values.push(argument.clone());
}
}
let Some(path) = path else {
let _ = stderr.write(
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",
);
return ExitStatus::FAILURE;
};
let value = values.join("\n");
let mut content = value;
if !content.is_empty() {
content.push('\n');
}
match self.write_redirect(&path, content.as_bytes(), append) {
Ok(()) => ExitStatus::SUCCESS,
Err(error) => {
let _ = stderr.write(format!("Set-Content : {error}\n").as_bytes());
ExitStatus::FAILURE
}
}
}
fn builtin_clear_host(&self, stdout: &mut dyn Output) -> ExitStatus {
let _ = stdout.write(b"\x1b[3J\x1b[H\x1b[2J");
ExitStatus::SUCCESS
}
fn builtin_start_sleep(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
let seconds = argv
.iter()
.skip(1)
.find(|argument| *argument != "-Seconds")
.and_then(|argument| argument.trim().parse::<f64>().ok())
.filter(|seconds| *seconds >= 0.0);
let Some(seconds) = seconds else {
let _ = stderr.write(
b"Start-Sleep : Cannot bind argument to parameter 'Seconds' because it is an empty string.\n",
);
return ExitStatus::FAILURE;
};
self.os
.engine()
.advance_time(std::time::Duration::from_secs_f64(seconds));
ExitStatus::SUCCESS
}
fn builtin_get_date(&self, stdout: &mut dyn Output) -> ExitStatus {
let _ = stdout.write(
format!(
"{}\n",
os::datetime::format_timestamp(self.os.engine().time(), "%a %b %d %H:%M:%S %Y")
)
.as_bytes(),
);
ExitStatus::SUCCESS
}
fn builtin_copy_item(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let mut recursive = false;
let mut operands: Vec<&String> = Vec::new();
for argument in argv.iter().skip(1) {
if argument == "-Recurse" || argument == "-r" {
recursive = true;
} else if argument.starts_with('-') {
continue;
} else {
operands.push(argument);
}
}
if operands.len() < 2 {
let _ = stderr.write(
b"Copy-Item : A positional parameter cannot be found that accepts argument ''.\n",
);
return ExitStatus::FAILURE;
}
let source_str = operands[0].clone();
let destination_str = operands[operands.len() - 1].clone();
let engine = self.os.engine();
let actor = Some(self.actor);
let source_path = match self.resolve_path(&source_str) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"Copy-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&source_str)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let source_object = match engine.lookup(actor, &source_path) {
Ok(object) => object,
Err(_) => {
let _ = stderr.write(
format!(
"Copy-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&source_str)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let destination_path = match self.resolve_path(&destination_str) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"Copy-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&destination_str)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let is_directory = engine.list(actor, source_object).is_ok();
if is_directory && !recursive {
let _ = stderr.write(
format!(
"Copy-Item : Access to the path '{}' is denied.\n",
self.display_path(&source_path)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
let (destination_directory, name) = match engine.lookup(actor, &destination_path) {
Ok(object) if engine.list(actor, object).is_ok() => {
let name = source_path.name().expect("source has name").to_owned();
(object, name)
}
Ok(_) => {
let name = destination_path
.name()
.expect("destination has name")
.to_owned();
let parent = destination_path
.parent()
.expect("destination has parent")
.clone();
match engine.lookup(actor, &parent) {
Ok(object) => (object, name),
Err(_) => {
let _ = stderr.write(
format!(
"Copy-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path(&parent)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
}
}
Err(_) => {
let name = destination_path
.name()
.expect("destination has name")
.to_owned();
let parent = destination_path
.parent()
.expect("destination has parent")
.clone();
match engine.lookup(actor, &parent) {
Ok(object) => (object, name),
Err(_) => {
let _ = stderr.write(
format!(
"Copy-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path(&parent)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
}
}
};
let name = match engine::Name::new(&name) {
Ok(name) => name,
Err(_) => {
let _ = stderr.write(b"Copy-Item : Illegal characters in path.\n");
return ExitStatus::FAILURE;
}
};
match engine.copy_object(actor, source_object, destination_directory, name) {
Ok(_) => ExitStatus::SUCCESS,
Err(error) => {
let _ = stderr.write(format!("Copy-Item : {error}\n").as_bytes());
ExitStatus::FAILURE
}
}
}
fn builtin_move_item(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let operands: Vec<&String> = argv
.iter()
.skip(1)
.filter(|argument| !argument.starts_with('-'))
.collect();
if operands.len() < 2 {
let _ = stderr.write(
b"Move-Item : A positional parameter cannot be found that accepts argument ''.\n",
);
return ExitStatus::FAILURE;
}
let source_str = operands[0].clone();
let destination_str = operands[operands.len() - 1].clone();
let engine = self.os.engine();
let actor = Some(self.actor);
let source_path = match self.resolve_path(&source_str) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"Move-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&source_str)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let source_object = match engine.lookup(actor, &source_path) {
Ok(object) => object,
Err(_) => {
let _ = stderr.write(
format!(
"Move-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&source_str)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let destination_path = match self.resolve_path(&destination_str) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"Move-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&destination_str)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let (destination_directory, name) = match engine.lookup(actor, &destination_path) {
Ok(object) if engine.list(actor, object).is_ok() => {
let name = source_path.name().expect("source has name").to_owned();
(object, name)
}
Ok(_) => {
let name = destination_path
.name()
.expect("destination has name")
.to_owned();
let parent = destination_path
.parent()
.expect("destination has parent")
.clone();
match engine.lookup(actor, &parent) {
Ok(object) => (object, name),
Err(_) => {
let _ = stderr.write(
format!(
"Move-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path(&parent)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
}
}
Err(_) => {
let name = destination_path
.name()
.expect("destination has name")
.to_owned();
let parent = destination_path
.parent()
.expect("destination has parent")
.clone();
match engine.lookup(actor, &parent) {
Ok(object) => (object, name),
Err(_) => {
let _ = stderr.write(
format!(
"Move-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path(&parent)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
}
}
};
let name = match engine::Name::new(&name) {
Ok(name) => name,
Err(_) => {
let _ = stderr.write(b"Move-Item : Illegal characters in path.\n");
return ExitStatus::FAILURE;
}
};
match engine.move_object(actor, source_object, destination_directory, Some(name)) {
Ok(_) => ExitStatus::SUCCESS,
Err(error) => {
let _ = stderr.write(format!("Move-Item : {error}\n").as_bytes());
ExitStatus::FAILURE
}
}
}
fn builtin_new_item(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let mut item_type = "File".to_owned();
let mut target: Option<String> = None;
for argument in argv.iter().skip(1) {
if argument == "-ItemType" {
if let Some(value) = argv
.iter()
.skip(1)
.skip(1)
.find(|value| *value != "-ItemType")
{
item_type = value.to_owned();
}
} else if argument.starts_with('-') {
continue;
} else if target.is_none() {
target = Some(argument.clone());
}
}
let Some(target) = target else {
let _ = stderr.write(
b"New-Item : Cannot bind argument to parameter 'Path' because it is an empty string.\n",
);
return ExitStatus::FAILURE;
};
let path = match self.resolve_path(&target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"New-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&target)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let engine = self.os.engine();
let actor = Some(self.actor);
if engine.lookup(actor, &path).is_ok() {
let _ = stderr.write(
format!(
"New-Item : An item with the specified name '{}' already exists.\n",
self.display_path(&path)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
let parent_path = path.parent().expect("path has parent").clone();
let parent = match engine.lookup(actor, &parent_path) {
Ok(parent) => parent,
Err(_) => {
let _ = stderr.write(
format!(
"New-Item : Cannot find path '{}' because it does not exist.\n",
self.display_path(&parent_path)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let name = path.name().expect("path has name").to_owned();
let name = match engine::Name::new(&name) {
Ok(name) => name,
Err(_) => {
let _ = stderr.write(b"New-Item : Illegal characters in path.\n");
return ExitStatus::FAILURE;
}
};
let directory = item_type.eq_ignore_ascii_case("Directory");
let result = if directory {
engine.create_directory(actor, parent, name)
} else {
engine.create_file(actor, parent, name, Some(Vec::new()))
};
match result {
Ok(_) => ExitStatus::SUCCESS,
Err(error) => {
let _ = stderr.write(format!("New-Item : {error}\n").as_bytes());
ExitStatus::FAILURE
}
}
}
fn builtin_get_process(
&self,
_argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let actor = Some(self.actor);
let engine = self.os.engine();
let processes = match self.os.processes() {
Ok(processes) => processes,
Err(error) => {
let _ = stderr.write(format!("Get-Process : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let processes = match os::process::list(engine, actor, processes.id()) {
Ok(processes) => processes,
Err(error) => {
let _ = stderr.write(format!("Get-Process : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let _ = stdout.write(
b"Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName\n------- ------ ----- ----- ------ -- -----------\n",
);
for (_, process) in processes {
let _ = stdout.write(
format!(
" 0 0 0 0 0.00 {:>5} {}\n",
process.pid, process.executable
)
.as_bytes(),
);
}
ExitStatus::SUCCESS
}
fn builtin_stop_process(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let mut id: Option<u32> = None;
let mut name: Option<String> = None;
for argument in argv.iter().skip(1) {
if argument == "-Id" {
id = argv
.iter()
.skip(1)
.find(|value| *value != "-Id")
.and_then(|value| value.parse().ok());
} else if argument == "-Name" {
name = argv.iter().skip(1).find(|value| *value != "-Name").cloned();
}
}
let actor = Some(self.actor);
let engine = self.os.engine();
let processes = match self.os.processes() {
Ok(processes) => processes,
Err(error) => {
let _ = stderr.write(format!("Stop-Process : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let processes = match os::process::list(engine, actor, processes.id()) {
Ok(processes) => processes,
Err(error) => {
let _ = stderr.write(format!("Stop-Process : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let mut terminated = false;
for (object, process) in processes {
let matches = if let Some(id) = id {
process.pid == id
} else if let Some(name) = &name {
process.executable.eq_ignore_ascii_case(name)
} else {
false
};
if matches {
terminated = true;
let _ = engine.delete(actor, object);
}
}
if !terminated {
if let Some(id) = id {
let _ = stderr.write(
format!(
"Stop-Process : Cannot find a process with the process identifier {id}. Verify the process identifier and call the cmdlet again.\n"
)
.as_bytes(),
);
} else {
let _ = stderr.write(
format!(
"Stop-Process : Cannot find a process with the name \"{}\". Verify the process name and call the cmdlet again.\n",
name.as_deref().unwrap_or_default()
)
.as_bytes(),
);
}
return ExitStatus::FAILURE;
}
ExitStatus::SUCCESS
}
fn builtin_get_itemproperty(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let registry = match self.os.registry() {
Ok(registry) => registry,
Err(error) => {
let _ = stderr.write(format!("Get-ItemProperty : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let path_arg = argv
.iter()
.skip(1)
.find(|argument| !argument.starts_with('-'))
.cloned()
.unwrap_or_default();
let (hive, path) = match Self::registry_path(&path_arg) {
Some(parts) => parts,
None => {
let _ = stderr.write(
format!(
"Get-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let actor = Some(self.actor);
let key = match registry.key(actor, &hive, &path) {
Ok(Some(key)) => key,
_ => {
let _ = stderr.write(
format!(
"Get-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let values = match registry.values(actor, key) {
Ok(values) => values,
Err(error) => {
let _ = stderr.write(format!("Get-ItemProperty : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let display = format!(
"{}\\{}",
os::windows::registry::RegistryState::hive_display(&hive),
path.replace('/', "\\")
);
for value in values {
let _ = stdout.write(format!("{:<18} : {}\n", value.name, value.data).as_bytes());
}
let _ = stdout.write(
format!(
"PSPath : Microsoft.PowerShell.Core\\Registry::{display}\nPSParentPath : Microsoft.PowerShell.Core\\Registry::{}\nPSParentChild : {}\nPSDrive : {}\nPSProvider : Microsoft.PowerShell.Core\\Registry\n",
parent_of_display(&display),
display.rsplit('\\').next().unwrap_or_default(),
hive.to_uppercase()
)
.as_bytes(),
);
ExitStatus::SUCCESS
}
fn builtin_set_itemproperty(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let registry = match self.os.registry() {
Ok(registry) => registry,
Err(error) => {
let _ = stderr.write(format!("Set-ItemProperty : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let path_arg = argv
.iter()
.skip(1)
.find(|argument| !argument.starts_with('-'))
.cloned()
.unwrap_or_default();
let (hive, path) = match Self::registry_path(&path_arg) {
Some(parts) => parts,
None => {
let _ = stderr.write(
format!(
"Set-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let mut name: Option<String> = None;
let mut value: Option<String> = None;
let args: Vec<String> = argv.iter().skip(1).cloned().collect();
let mut index = 0;
while index < args.len() {
match args[index].to_ascii_lowercase().as_str() {
"-name" => {
index += 1;
name = args.get(index).cloned();
}
"-value" => {
index += 1;
value = args.get(index).cloned();
}
"-pathtype" | "-type" => {
index += 1;
}
_ => {}
}
index += 1;
}
let (Some(name), Some(value)) = (name, value) else {
let _ = stderr.write(b"Set-ItemProperty : Cannot bind argument to parameter 'Name' because it is an empty string.\n");
return ExitStatus::FAILURE;
};
match registry.set_value(Some(self.actor), &hive, &path, &name, "REG_SZ", &value) {
Ok(()) => ExitStatus::SUCCESS,
Err(error) => {
let _ = stderr.write(format!("Set-ItemProperty : {error}\n").as_bytes());
ExitStatus::FAILURE
}
}
}
fn builtin_remove_itemproperty(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let registry = match self.os.registry() {
Ok(registry) => registry,
Err(error) => {
let _ = stderr.write(format!("Remove-ItemProperty : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let path_arg = argv
.iter()
.skip(1)
.find(|argument| !argument.starts_with('-'))
.cloned()
.unwrap_or_default();
let (hive, path) = match Self::registry_path(&path_arg) {
Some(parts) => parts,
None => {
let _ = stderr.write(
format!(
"Remove-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let mut name: Option<String> = None;
let args: Vec<String> = argv.iter().skip(1).cloned().collect();
let mut index = 0;
while index < args.len() {
if args[index].eq_ignore_ascii_case("-Name") {
index += 1;
name = args.get(index).cloned();
}
index += 1;
}
let Some(name) = name else {
let _ = stderr.write(b"Remove-ItemProperty : Cannot bind argument to parameter 'Name' because it is an empty string.\n");
return ExitStatus::FAILURE;
};
let actor = Some(self.actor);
let key = match registry.key(actor, &hive, &path) {
Ok(Some(key)) => key,
_ => {
let _ = stderr.write(
format!(
"Remove-ItemProperty : Cannot find path '{path_arg}' because it does not exist.\n"
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
match registry.delete_value(actor, key, &name) {
Ok(true) => ExitStatus::SUCCESS,
Ok(false) => {
let _ = stderr.write(
format!(
"Remove-ItemProperty : Cannot find path '{path_arg}\\{name}' because it does not exist.\n"
)
.as_bytes(),
);
ExitStatus::FAILURE
}
Err(error) => {
let _ = stderr.write(format!("Remove-ItemProperty : {error}\n").as_bytes());
ExitStatus::FAILURE
}
}
}
fn registry_path(path: &str) -> Option<(String, String)> {
let (hive, rest) = path.split_once(':')?;
if !os::windows::registry::RegistryState::is_hive(hive) {
return None;
}
Some((
hive.to_owned(),
rest.trim_start_matches('\\').replace('\\', "/"),
))
}
fn builtin_get_alias(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.len() > 1 {
let mut exit_status = ExitStatus::SUCCESS;
for name in argv.iter().skip(1) {
let key = name.trim_start_matches('-').to_lowercase();
if let Some(target) = self.aliases.get(&key) {
let _ = stdout.write(format!("Alias {key} -> {target}\n").as_bytes());
} else {
let _ = stderr.write(
format!(
"Get-Alias: The term '{name}' is not recognized as the name of a cmdlet, function, script file, or operable program.\n"
)
.as_bytes(),
);
exit_status = ExitStatus::FAILURE;
}
}
return exit_status;
}
for (name, target) in &self.aliases {
let _ = stdout.write(format!("Alias {name} -> {target}\n").as_bytes());
}
ExitStatus::SUCCESS
}
fn builtin_set_alias(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
if argv.len() < 3 {
let _ = stderr.write(b"Set-Alias: usage: Set-Alias [-Name] name [-Value] cmdlet\n");
return ExitStatus::USAGE;
}
let mut name = None;
let mut value = None;
let mut index = 1;
while index < argv.len() {
match argv[index].as_str() {
"-Name" => {
name = argv.get(index + 1).cloned();
index += 2;
}
"-Value" => {
value = argv.get(index + 1).cloned();
index += 2;
}
"-Scope" | "-Option" | "-Force" | "-PassThru" => {
index += 1;
if matches!(argv[index - 1].as_str(), "-Scope" | "-Option") {
index += 1;
}
}
argument if !argument.starts_with('-') && name.is_none() => {
name = Some(argument.to_owned());
index += 1;
}
argument if !argument.starts_with('-') && value.is_none() => {
value = Some(argument.to_owned());
index += 1;
}
_ => index += 1,
}
}
let (Some(name), Some(value)) = (name, value) else {
let _ = stderr.write(b"Set-Alias: usage: Set-Alias [-Name] name [-Value] cmdlet\n");
return ExitStatus::USAGE;
};
self.aliases.insert(name.to_lowercase(), value);
ExitStatus::SUCCESS
}
fn builtin_history(&self, stdout: &mut dyn Output) -> ExitStatus {
for (index, line) in self.history.iter().enumerate() {
let _ = stdout.write(format!("{:5} {}\n", index + 1, line).as_bytes());
}
ExitStatus::SUCCESS
}
fn builtin_get_localuser(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let users = self.os.users().users();
let name_width = users
.iter()
.map(|user| user.name().len())
.max()
.unwrap_or(0)
.max(4)
+ 1;
let enabled_width = "Enabled".len() + 1;
let header = format!(
"{:<name_width$}{:<enabled_width$}Description\n",
"Name", "Enabled"
);
let dashes = format!(
"{:<name_width$}{:<enabled_width$}-----------\n",
"----", "-------"
);
if let Some(target) = argv.get(1) {
let Some(user) = users
.iter()
.find(|user| user.name().eq_ignore_ascii_case(target))
else {
let _ = stderr.write(
format!("Get-LocalUser: Cannot find an object with identity: '{target}'.\n")
.as_bytes(),
);
return ExitStatus::FAILURE;
};
let row = format!(
"{:<name_width$}{:<enabled_width$}\n",
user.name(),
if user.enabled() { "True" } else { "False" }
);
let _ = stdout.write(header.as_bytes());
let _ = stdout.write(dashes.as_bytes());
let _ = stdout.write(row.as_bytes());
return ExitStatus::SUCCESS;
}
let _ = stdout.write(header.as_bytes());
let _ = stdout.write(dashes.as_bytes());
for user in users {
let row = format!(
"{:<name_width$}{:<enabled_width$}\n",
user.name(),
if user.enabled() { "True" } else { "False" }
);
let _ = stdout.write(row.as_bytes());
}
ExitStatus::SUCCESS
}
fn builtin_get_localgroup(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let groups = self.os.groups();
let name_width = groups
.iter()
.map(|group| group.name.len())
.max()
.unwrap_or(0)
.max(4)
+ 1;
let header = format!("{:<name_width$}Description\n", "Name");
let dashes = format!("{:<name_width$}-----------\n", "----");
if let Some(target) = argv.get(1) {
let Some(group) = groups
.iter()
.find(|group| group.name.eq_ignore_ascii_case(target))
else {
let _ = stderr.write(
format!("Get-LocalGroup: Cannot find an object with identity: '{target}'.\n")
.as_bytes(),
);
return ExitStatus::FAILURE;
};
let _ = stdout.write(header.as_bytes());
let _ = stdout.write(dashes.as_bytes());
let _ = stdout.write(format!("{:<name_width$}\n", group.name).as_bytes());
return ExitStatus::SUCCESS;
}
let _ = stdout.write(header.as_bytes());
let _ = stdout.write(dashes.as_bytes());
for group in groups {
let _ = stdout.write(format!("{:<name_width$}\n", group.name).as_bytes());
}
ExitStatus::SUCCESS
}
fn builtin_get_service(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let services = match self.os.service_state() {
Ok(services) => services,
Err(error) => {
let _ = stderr.write(format!("Get-Service : {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
if let Some(target) = argv.get(1) {
let Some(object) = services.find(target).unwrap_or(None) else {
let _ = stderr.write(
format!(
"Get-Service : Cannot find any service with service name '{target}'.\n"
)
.as_bytes(),
);
return ExitStatus::FAILURE;
};
let (name, state) = services
.entries()
.unwrap_or_default()
.into_iter()
.find(|(_, entry_object)| *entry_object == object)
.map(|(name, _)| (name, services.state(object)))
.unwrap_or_else(|| (target.to_owned(), services.state(object)));
let _ = stdout.write(
format!(
"Status Name DisplayName\n------ ---- -----------\n{:<7} {:<18} {}\n",
state, name, name
)
.as_bytes(),
);
return ExitStatus::SUCCESS;
}
let _ = stdout.write(
b"Status Name DisplayName\n------ ---- -----------\n",
);
for (entry, object) in services.entries().unwrap_or_default() {
let state = services.state(object);
let _ = stdout.write(format!("{:<7} {:<18} {}\n", state, entry, entry).as_bytes());
}
ExitStatus::SUCCESS
}
fn builtin_get_item(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let Some(target) = argv.get(1) else {
let _ = stderr.write(b"Get-Item: missing path\n");
return ExitStatus::USAGE;
};
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"Get-Item: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(target)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
match self.os.engine().lookup(Some(self.actor), &path) {
Ok(object) => {
let name = path.name().map(str::to_owned).unwrap_or_default();
let directory = self.os.engine().list(Some(self.actor), object).is_ok();
let kind = if directory { "Directory" } else { "File" };
let parent = path.parent().unwrap_or_else(|| path.clone());
let _ = stdout.write(
format!(
" Directory: {}\n\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n{kind} {name}\n",
self.display_path(&parent)
)
.as_bytes(),
);
}
Err(_) => {
let _ = stderr.write(
format!(
"Get-Item: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(target)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
}
ExitStatus::SUCCESS
}
fn builtin_remove_item(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let _ = stdout;
let mut recursive = false;
let mut targets: Vec<&String> = Vec::new();
for argument in argv.iter().skip(1) {
if argument == "-Recurse" || argument == "-r" {
recursive = true;
} else if argument.starts_with('-') {
continue;
} else {
targets.push(argument);
}
}
let mut exit_status = ExitStatus::SUCCESS;
for target in targets {
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"Remove-Item: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(target)
)
.as_bytes(),
);
exit_status = ExitStatus::FAILURE;
continue;
}
};
match self.os.engine().lookup(Some(self.actor), &path) {
Ok(object) => {
let is_directory = self.os.engine().list(Some(self.actor), object).is_ok();
if is_directory && !recursive {
let _ = stderr.write(
format!(
"Remove-Item: Cannot remove item '{}': access to the path is denied.\n",
self.display_path(&path)
)
.as_bytes(),
);
exit_status = ExitStatus::FAILURE;
continue;
}
if self.os.engine().delete(Some(self.actor), object).is_err() {
exit_status = ExitStatus::FAILURE;
}
}
Err(_) => {
let _ = stderr.write(
format!(
"Remove-Item: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(target)
)
.as_bytes(),
);
exit_status = ExitStatus::FAILURE;
}
}
}
exit_status
}
fn builtin_cd(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
let Some(target) = argv.get(1) else {
return ExitStatus::SUCCESS;
};
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"cd: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(target)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let exists = self
.os
.engine()
.lookup(Some(self.actor), &path)
.is_ok_and(|object| self.os.engine().children(Some(self.actor), object).is_ok());
if !exists {
let _ = stderr.write(
format!(
"cd: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(target)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
self.cwd = path;
ExitStatus::SUCCESS
}
fn builtin_pwd(&self, stdout: &mut dyn Output) -> ExitStatus {
let _ = stdout.write(format!("{}\n", self.display_path(&self.cwd)).as_bytes());
ExitStatus::SUCCESS
}
fn builtin_echo(&self, argv: &[String], stdout: &mut dyn Output) -> ExitStatus {
let text = argv[1..].join(" ");
let _ = stdout.write(format!("{text}\n").as_bytes());
ExitStatus::SUCCESS
}
fn builtin_cat(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.len() < 2 {
let _ = stderr.write(b"Get-Content: missing path\n");
return ExitStatus::USAGE;
}
let mut exit_status = ExitStatus::SUCCESS;
for path_str in argv.iter().skip(1) {
let path = match self.resolve_path(path_str) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"Get-Content: Cannot find path '{path_str}' because it does not exist.\n"
)
.as_bytes(),
);
exit_status = ExitStatus::FAILURE;
continue;
}
};
let content = self
.os
.engine()
.lookup(Some(self.actor), &path)
.ok()
.and_then(|object| {
self.os
.engine()
.read(Some(self.actor), object)
.ok()
.flatten()
});
match content {
Some(bytes) => {
let _ = stdout.write(&bytes);
}
None => {
let _ = stderr.write(
format!(
"Get-Content: Cannot find path '{path_str}' because it does not exist.\n"
)
.as_bytes(),
);
exit_status = ExitStatus::FAILURE;
}
}
}
exit_status
}
fn builtin_ls(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let target = argv.get(1).cloned().unwrap_or_else(|| self.cwd.to_string());
let path = match self.resolve_path(&target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(
format!(
"ls: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&target)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let directory = match self.os.engine().lookup(Some(self.actor), &path) {
Ok(object) => object,
Err(_) => {
let _ = stderr.write(
format!(
"ls: Cannot find path '{}' because it does not exist.\n",
self.display_path_of(&target)
)
.as_bytes(),
);
return ExitStatus::FAILURE;
}
};
let Ok(entries) = self.os.engine().list(Some(self.actor), directory) else {
let name = path.name().unwrap_or(&target).to_owned();
let _ = stdout.write(format!("{name}\n").as_bytes());
return ExitStatus::SUCCESS;
};
for (name, _) in entries {
let _ = stdout.write(format!("{}\n", name.as_str()).as_bytes());
}
ExitStatus::SUCCESS
}
}
impl<'os> crate::Shell for PowerShell<'os> {
fn name(&self) -> &'static str {
"powershell"
}
fn actor(&self) -> engine::ActorId {
self.actor
}
fn environment(&self) -> &os::Environment {
&self.environment
}
fn engine(&self) -> &Engine {
self.os.engine()
}
fn boot_time(&self) -> engine::Timestamp {
self.os.boot_time()
}
fn hostname(&self) -> String {
self.environment
.get("COMPUTERNAME")
.unwrap_or("vce")
.to_owned()
}
fn cwd(&self) -> &VirtualPath {
&self.cwd
}
fn banner(&self) -> Option<String> {
Some(
"Windows PowerShell\nCopyright (C) Microsoft Corporation. All rights reserved.\n"
.to_owned(),
)
}
fn prompt(&self, hostname: &str) -> String {
let _ = hostname;
format!("PS {}> ", self.display_path(&self.cwd))
}
fn set_terminal_size(&mut self, rows: u16, cols: u16) {
self.environment.set("COLUMNS", cols.to_string());
self.environment.set("LINES", rows.to_string());
}
fn execute(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
self.run_line(line, stdin, stdout, stderr)
}
fn execute_with_terminal(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
_terminal: Option<&mut dyn Terminal>,
) -> ExitStatus {
self.run_line(line, stdin, stdout, stderr)
}
fn take_exit_status(&mut self) -> Option<ExitStatus> {
self.exit_request.take()
}
fn history(&self) -> &[String] {
&self.history
}
fn record_history(&mut self, line: &str) {
if line.trim().is_empty() {
return;
}
self.history.push(line.to_owned());
if self.history.len() > crate::HISTORY_LIMIT {
self.history.remove(0);
}
}
}
fn word_text(token: &Token, source: &str, environment: &Environment) -> Option<String> {
let text = token.text(source);
match token.kind {
TokenKind::Whitespace
| TokenKind::Newline
| TokenKind::LineComment
| TokenKind::BlockComment
| TokenKind::Semicolon
| TokenKind::Pipe
| TokenKind::LCurly
| TokenKind::RCurly
| TokenKind::LParen
| TokenKind::RParen
| TokenKind::Comma => None,
TokenKind::StringLiteral => Some(unquote(text)),
TokenKind::StringExpandable => Some(expand_string(text, environment)),
TokenKind::Variable => {
let name = text.trim_start_matches('$');
Some(environment.get(name).unwrap_or("").to_owned())
}
TokenKind::Operator(_) if is_redirect(token, source) => None,
_ => Some(text.to_owned()),
}
}
fn is_redirect(token: &Token, source: &str) -> bool {
let text = token.text(source);
matches!(text, ">" | ">>" | "<")
}
fn unquote(text: &str) -> String {
if let Some(inner) = text
.strip_prefix('\'')
.and_then(|value| value.strip_suffix('\''))
{
inner.replace("''", "'")
} else if let Some(inner) = text
.strip_prefix('"')
.and_then(|value| value.strip_suffix('"'))
{
inner.to_owned()
} else {
text.to_owned()
}
}
fn expand_string(text: &str, environment: &Environment) -> String {
let mut result = String::new();
let mut chars = text.trim_matches('"').chars().peekable();
while let Some(ch) = chars.next() {
if ch == '$' {
let mut name = String::new();
while let Some(&next) = chars.peek() {
if next.is_alphanumeric() || next == '_' {
name.push(next);
chars.next();
} else {
break;
}
}
result.push_str(environment.get(&name).unwrap_or(""));
} else {
result.push(ch);
}
}
result
}
fn read_file(shell: &PowerShell<'_>, path: &str) -> BytesInput {
let engine = shell.os.engine();
let actor = Some(shell.actor);
let Ok(path) = shell.resolve_path(path) else {
return BytesInput::new(Vec::new());
};
let content = engine
.lookup(actor, &path)
.ok()
.and_then(|object| engine.read(actor, object).ok().flatten())
.unwrap_or_default();
BytesInput::new(content)
}
fn split_statements(tokens: &[Token]) -> Vec<Vec<Token>> {
let mut statements = Vec::new();
let mut current = Vec::new();
for token in tokens {
if matches!(token.kind, TokenKind::Semicolon | TokenKind::Newline) {
if !current.is_empty() {
statements.push(std::mem::take(&mut current));
}
} else {
current.push(*token);
}
}
if !current.is_empty() {
statements.push(current);
}
statements
}
fn split_pipeline(tokens: &[Token]) -> Vec<Vec<Token>> {
let mut stages = Vec::new();
let mut current = Vec::new();
for token in tokens {
if token.kind == TokenKind::Pipe {
if !current.is_empty() {
stages.push(std::mem::take(&mut current));
}
} else {
current.push(*token);
}
}
if !current.is_empty() {
stages.push(current);
}
stages
}
fn parent_of_display(display: &str) -> String {
match display.rfind('\\') {
Some(index) => display[..index].to_owned(),
None => String::new(),
}
}
fn default_aliases() -> [(&'static str, &'static str); 37] {
[
("cat", "Get-Content"),
("cd", "Set-Location"),
("chdir", "Set-Location"),
("clear", "Clear-Host"),
("cls", "Clear-Host"),
("copy", "Copy-Item"),
("cp", "Copy-Item"),
("del", "Remove-Item"),
("dir", "Get-ChildItem"),
("echo", "Write-Output"),
("gc", "Get-Content"),
("gci", "Get-ChildItem"),
("gi", "Get-Item"),
("gl", "Get-Location"),
("h", "Get-History"),
("history", "Get-History"),
("ls", "Get-ChildItem"),
("gps", "Get-Process"),
("kill", "Stop-Process"),
("mi", "Move-Item"),
("mv", "Move-Item"),
("ni", "New-Item"),
("ps", "Get-Process"),
("pwd", "Get-Location"),
("gp", "Get-ItemProperty"),
("sp", "Set-ItemProperty"),
("rp", "Remove-ItemProperty"),
("rd", "Remove-Item"),
("rm", "Remove-Item"),
("rmdir", "Remove-Item"),
("sal", "Set-Alias"),
("sc", "Set-Content"),
("sleep", "Start-Sleep"),
("sl", "Set-Location"),
("gd", "Get-Date"),
("type", "Get-Content"),
("write", "Write-Output"),
]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Shell;
use engine::Timestamp;
use os::HostIdentity;
use os::windows::Windows;
fn session() -> (Box<PowerShell<'static>>, &'static Windows) {
let windows = Box::leak(Box::new(
Windows::with_identity(
&HostIdentity::new("demo", "demo-host"),
Timestamp::from_nanos(1_000_000),
)
.unwrap(),
));
let actor = windows.authenticate("demo", "demo").unwrap();
let shell =
Box::new(PowerShell::new(windows, actor, windows.environment().clone()).unwrap());
(shell, windows)
}
#[test]
fn powershell_runs_builtins_and_prompt() {
let (mut shell, _windows) = session();
assert_eq!(shell.prompt("demo-host"), "PS C:\\Users\\demo> ");
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
shell.execute(
"echo hello",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
assert_eq!(stdout.bytes(), b"hello\n");
shell.execute("pwd", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
assert!(String::from_utf8_lossy(stdout.bytes()).contains("C:\\Users\\demo"));
}
#[test]
fn powershell_lists_the_profile() {
let (mut shell, _windows) = session();
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
shell.execute("ls", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
let text = String::from_utf8(stdout.into_bytes()).unwrap();
assert!(text.contains("Desktop"), "profile folders: {text}");
assert!(text.contains("Documents"));
}
#[test]
fn powershell_reports_missing_commands() {
let (mut shell, _windows) = session();
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
let status = shell.execute(
"not-a-command",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
assert_eq!(status, ExitStatus::NOT_FOUND);
assert!(String::from_utf8_lossy(stderr.bytes()).contains("not recognized"));
}
#[test]
fn powershell_aliases_resolve_to_cmdlets() {
let (mut shell, _windows) = session();
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
shell.execute(
"echo hello > t.txt",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
let status = shell.execute(
"cat t.txt",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(stdout.bytes(), b"hello\n");
let mut alias_out = BytesOutput::new();
shell.execute(
"Get-Alias cat",
&mut BytesInput::new(b""),
&mut alias_out,
&mut stderr,
);
assert_eq!(
String::from_utf8_lossy(alias_out.bytes()),
"Alias cat -> Get-Content\n"
);
}
#[test]
fn set_content_preserves_dash_prefixed_values() {
let (mut shell, _windows) = session();
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
let status = shell.execute(
"Set-Content -Path Desktop\\work-order.txt -Value '- first item' '--------' 'company''s policy'",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
assert_eq!(
status,
ExitStatus::SUCCESS,
"{}",
String::from_utf8_lossy(stderr.bytes())
);
let mut contents = BytesOutput::new();
let status = shell.execute(
"Get-Content Desktop\\work-order.txt",
&mut BytesInput::new(b""),
&mut contents,
&mut stderr,
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(
contents.bytes(),
b"- first item\n--------\ncompany's policy\n"
);
}
#[test]
fn powershell_cd_and_variables() {
let (mut shell, _windows) = session();
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
shell.execute(
"cd C:\\Windows\\System32",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
assert_eq!(shell.cwd().to_string(), "/Windows/System32");
shell.execute("pwd", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
assert!(String::from_utf8_lossy(stdout.bytes()).contains("C:\\Windows\\System32"));
let status = shell.execute(
"cd C:/Users/demo/Desktop/",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
assert_eq!(status, ExitStatus::SUCCESS);
assert_eq!(shell.cwd().to_string(), "/Users/demo/Desktop");
}
#[test]
fn cd_backslash_goes_to_root() {
let (mut shell, _) = session();
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
shell.execute(
"cd C:\\Windows",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
assert_eq!(shell.cwd().to_string(), "/Windows");
stdout = BytesOutput::new();
stderr = BytesOutput::new();
let status = shell.execute("cd \\", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
assert_eq!(status, os::runtime::ExitStatus::SUCCESS);
assert_eq!(shell.cwd().to_string(), "/");
shell.execute(
"cd C:\\Windows",
&mut BytesInput::new(b""),
&mut stdout,
&mut stderr,
);
stdout = BytesOutput::new();
stderr = BytesOutput::new();
let status = shell.execute("cd\\", &mut BytesInput::new(b""), &mut stdout, &mut stderr);
assert_eq!(status, os::runtime::ExitStatus::SUCCESS);
assert_eq!(shell.cwd().to_string(), "/");
}
#[test]
fn needs_continuation_for_powershell_is_false_for_cd_backslash() {
let (shell, _) = session();
assert!(!shell.needs_continuation("cd \\\n"));
assert!(!shell.needs_continuation("cd C:\\Windows\n"));
}
}