powershell_script/builder.rs
1use std::collections::VecDeque;
2
3use crate::PsScript;
4
5/// Builds a `PsScript` instance with configurable options for running your
6/// script.
7pub struct PsScriptBuilder {
8 args: VecDeque<&'static str>,
9 no_profile: bool,
10 non_interactive: bool,
11 hidden: bool,
12 print_commands: bool,
13}
14
15impl PsScriptBuilder {
16 /// Creates a default builder with no_profile, non_interactive and hidden
17 /// options set to true and print_commands set to false.
18 pub fn new() -> Self {
19 Self::default()
20 }
21
22 /// Prevents environment specifc scripts from being loaded. See [NoProfile parameter](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_profiles?view=powershell-7.2#the-noprofile-parameter)
23 pub fn no_profile(mut self, flag: bool) -> Self {
24 self.no_profile = flag;
25 self
26 }
27
28 /// Runs the script in non-interactive mode, which does not present an
29 /// interactive prompt to the user. See [NonInteractive flag](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-noninteractive)
30 pub fn non_interactive(mut self, flag: bool) -> Self {
31 self.non_interactive = flag;
32 self
33 }
34
35 /// Prevents PowerShell window from being shown by creating a console
36 /// window with the CREATE_NO_WINDOW flag set. See [creation flags](https://docs.microsoft.com/en-us/windows/win32/procthread/process-creation-flags)
37 ///
38 /// ## Note
39 /// On any other platform than Windows this is currently a no-op.
40 pub fn hidden(mut self, flag: bool) -> Self {
41 self.hidden = flag;
42 self
43 }
44
45 /// If set to `true` it will print each command to `stdout` as they're run.
46 /// This can be particularely useful when debugging.
47 pub fn print_commands(mut self, flag: bool) -> Self {
48 self.print_commands = flag;
49 self
50 }
51
52 pub fn build(self) -> PsScript {
53 let mut args = self.args;
54 if self.non_interactive {
55 args.push_front("-NonInteractive");
56 }
57
58 if self.no_profile {
59 args.push_front("-NoProfile");
60 }
61
62 PsScript {
63 args: args.make_contiguous().to_vec(),
64 hidden: self.hidden,
65 print_commands: self.print_commands,
66 }
67 }
68}
69
70impl Default for PsScriptBuilder {
71
72 /// Creates a default builder with `no_profile`, `non_interactive` and `hidden`
73 /// options set to `true` and `print_commands` set to `false`.
74 fn default() -> Self {
75 let mut args = VecDeque::new();
76 args.push_back("-Command");
77 args.push_back("-");
78
79 Self {
80 args,
81 no_profile: true,
82 non_interactive: true,
83 hidden: true,
84 print_commands: false,
85 }
86 }
87}