├── .gitignore ├── CHEATSHEET.md ├── CONTRIBUTING.md ├── LICENSE ├── NoPowerShell.cna ├── Pictures ├── CurrentlySupportedCommands.png ├── NoPowerShellDll.png └── SampleCommands.png ├── README.md └── Source ├── DllExport.bat ├── NoPowerShell.sln └── NoPowerShell ├── App.config ├── Arguments ├── Argument.cs ├── ArgumentList.cs ├── BoolArgument.cs ├── IntegerArgument.cs └── StringArgument.cs ├── Commands ├── ActiveDirectory │ ├── GetADComputerCommand.cs │ ├── GetADGroupCommand.cs │ ├── GetADGroupMemberCommand.cs │ ├── GetADObjectCommand.cs │ ├── GetADTrustCommand.cs │ └── GetADUserCommand.cs ├── Additional │ ├── GetRemoteSmbShareCommand.cs │ ├── GetWhoamiCommand.cs │ └── GetWinStationCommand.cs ├── Archive │ ├── CompressArchiveCommand.cs │ └── ExpandArchiveCommand.cs ├── Core │ ├── GetCommandCommand.cs │ ├── GetHelpCommand.cs │ └── WhereObjectCommand.cs ├── DnsClient │ ├── GetDnsClientCacheCommand.cs │ └── ResolveDnsNameCommand.cs ├── LocalAccounts │ ├── GetLocalGroupCommand.cs │ ├── GetLocalGroupMemberCommand.cs │ └── GetLocalUserCommand.cs ├── Management │ ├── CopyItemCommand.cs │ ├── GetChildItemCommand.cs │ ├── GetClipboardCommand.cs │ ├── GetComputerInfoCommand.cs │ ├── GetContentCommand.cs │ ├── GetHotFixCommand.cs │ ├── GetItemPropertyCommand.cs │ ├── GetItemPropertyValueCommand.cs │ ├── GetPSDriveCommand.cs │ ├── GetProcessCommand.cs │ ├── GetWmiObjectCommand.cs │ ├── InvokeWmiMethodCommand.cs │ ├── RemoveItemCommand.cs │ ├── SetClipboardCommand.cs │ └── StopProcessCommand.cs ├── NetTCPIP │ ├── GetNetIPAddressCommand.cs │ ├── GetNetNeighborCommand.cs │ ├── GetNetRouteCommand.cs │ ├── GetNetTCPConnectionCommand.cs │ └── TestNetConnectionCommand.cs ├── PSCommand.cs ├── SmbShare │ ├── GetSmbMappingCommand.cs │ └── GetSmbShareCommand.cs ├── TemplateCommand.cs └── Utility │ ├── ExportCsvCommand.cs │ ├── FormatListCommand.cs │ ├── FormatTableCommand.cs │ ├── InvokeWebRequestCommand.cs │ ├── MeasureObjectCommand.cs │ ├── OutFileCommand.cs │ ├── SelectObjectCommand.cs │ ├── SortObjectCommand.cs │ └── WriteOutputCommand.cs ├── HelperClasses ├── CaseInsensitiveList.cs ├── CommandResult.cs ├── DNSHelper.cs ├── Exceptions.cs ├── HelpEntries.cs ├── LDAPHelper.cs ├── PipeParser.cs ├── PipelineHelper.cs ├── ProviderHelper.cs ├── ReflectionHelper.cs ├── RegistryHelper.cs ├── ResultPrinter.cs ├── ResultRecord.cs └── WmiHelper.cs ├── NoPowerShell.csproj ├── Program.cs ├── ProgramDll.cs ├── Properties └── AssemblyInfo.cs ├── lib └── BOF.NET │ ├── net35 │ ├── BOFNET.dll │ ├── bofnet.cna │ ├── bofnet_execute.cpp.x64.obj │ └── bofnet_execute.cpp.x86.obj │ └── net40 │ ├── BOFNET.dll │ ├── bofnet.cna │ ├── bofnet_execute.cpp.x64.obj │ └── bofnet_execute.cpp.x86.obj └── packages.config /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Add your own cmdlets by submitting a pull request. 4 | ## Aim 5 | - Maintain .NET 2.0 compatibility in order to support the broadest range of operating systems 6 | - In case for whatever reason .NET 2.0 compatibility is not possible, add the `#if` preprocessor directive to the class specifying the unsupported .NET versions (for examples check the `*-Archive` cmdlets) 7 | 8 | ## Instructions 9 | Use the TemplateCommand.cs file in the Commands folder to construct new cmdlets. The TemplateCommand cmdlet is hidden from the list of available cmdlets, but can be called in order to understand its workings. This command looks as follows: `Get-TemplateCommand [-MyFlag] -MyInteger [Int32] -MyString [Value]` and is also accessible via alias `gtc`. 10 | 11 | ### Example usages 12 | | Action | Command | 13 | | - | - | 14 | | Simply run with default values | `gtc` | 15 | | Run with the -MyFlag parameter which executes the 'else' statement | `gtc -MyFlag` | 16 | | Run with the -MyInteger parameter which changes the number of iterations from its default number of 5 iterations to whatever number is provided | `gtc -MyInteger 10` | 17 | | Run with the -MyString parameter which changes the text that is printed from its default value of 'Hello World' to whatever string is provided | `gtc -MyString "Bye PowerShell"` | 18 | | Combination of parameters | `gtc -MyInteger 10 -MyString "Bye PowerShell"` | 19 | | Combination of parameters - Using fact that MyString is the only mandatory parameter for this command | `gtc -MyInteger 10 "Bye PowerShell"` | 20 | | Command in combination with a couple of data manipulators in the pipe | `gtc "Bye PowerShell" -MyInteger 30 \| ? Attribute2 -Like Line1* \| select Attribute2 \| fl` | 21 | 22 | Execute the following steps to implement your own cmdlet: 23 | 1. Download Visual Studio Community from https://visualstudio.microsoft.com/downloads/ 24 | * In the installer select the **.NET desktop development** component. 25 | * From this component no optional modules are required for developing NoPowerShell modules. 26 | 2. Make sure to have the .NET 2 framework installed: `OptionalFeatures.exe` -> '.NET Framework 3.5 (includes .NET 2.0 and 3.0)'. 27 | 3. Clone this repository and create a copy of the **TemplateCommand.cs** file. 28 | * In case you are implementing a native PowerShell command, place it in folder the corresponding to the _Source_ attribute when executing in PowerShell: `Get-Command My-Commandlet`. 29 | * Moreover, use the name of the _Source_ attribute in the command's namespace. 30 | * Example of a native command: `Get-Command Get-Process` -> Source: `Microsoft.PowerShell.Management` -> Place the .cs file in the **Management** subfolder and use `NoPowerShell.Commands.Management` namespace. 31 | * In case it is a non-native command, place it in the **Additional** folder and use the `NoPowerShell.Commands.Additional` namespace. 32 | 4. Update the `TemplateCommand` classname and its constructor name. 33 | 5. Update the static **Aliases** variable to the command and aliases you want to use to call this cmdlet. For native PowerShell commands you can lookup the aliases using `Get-Alias | ? ResolvedCommandName -EQ My-Commandlet` to obtain the list of aliases. Always make sure the full command is the first "alias", for example: `Get-Alias | ? ResolvedCommandName -EQ Get-Process` -> Aliases are: `Get-Process`, `gps`, `ps` 34 | 6. Update the static **Synopsis** variable to a small text that describes the command. This will be shown in the help. 35 | 7. Update the arguments supported by the command by adding _StringArguments_, _BoolArguments_ and _IntegerArguments_ to the static **SupportedArguments** variable. 36 | 8. In the Execute function: 37 | 1. Fetch the values of the _StringArguments_, _BoolArguments_ and _IntegerArguments_ as shown in the examples; 38 | 2. Based on the parameters provided by the user, perform your actions; 39 | 3. Make sure all results are stored in the `_results` variable. 40 | 9. Remove all of the template sample code and comments from the file to keep the source tidy. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2018, Arris Huijgen 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | * Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /NoPowerShell.cna: -------------------------------------------------------------------------------- 1 | # _ _ ____ ____ _ _ _ 2 | # | \ | | ___ | _ \ _____ _____ _ __/ ___|| |__ ___| | | 3 | # | \| |/ _ \| |_) / _ \ \ /\ / / _ \ '__\___ \| '_ \ / _ \ | | 4 | # | |\ | (_) | __/ (_) \ V V / __/ | ___) | | | | __/ | | 5 | # |_| \_|\___/|_| \___/ \_/\_/ \___|_| |____/|_| |_|\___|_|_| 6 | # 7 | # @bitsadmin 8 | # https://github.com/bitsadmin 9 | # 10 | 11 | $binary = "NoPowerShell.exe"; 12 | $help = "Execute a command via the reflective NoPowerShell commandline"; 13 | beacon_command_register("nps", $help, "Use: nps [command]\n\n$help"); 14 | 15 | alias nps 16 | { 17 | if(!-exists $binary) 18 | { 19 | berror($1, "NoPowerShell binary cannot be found at $binary"); 20 | return; 21 | } 22 | $args = replace($0, "nps ", ""); 23 | bexecute_assembly($1, $binary, $args); 24 | } 25 | -------------------------------------------------------------------------------- /Pictures/CurrentlySupportedCommands.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Pictures/CurrentlySupportedCommands.png -------------------------------------------------------------------------------- /Pictures/NoPowerShellDll.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Pictures/NoPowerShellDll.png -------------------------------------------------------------------------------- /Pictures/SampleCommands.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Pictures/SampleCommands.png -------------------------------------------------------------------------------- /Source/NoPowerShell.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28803.156 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NoPowerShell", "NoPowerShell\NoPowerShell.csproj", "{555AD0AC-1FDB-4016-8257-170A74CB2F55}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug BOF|Any CPU = Debug BOF|Any CPU 11 | Debug BOF|x64 = Debug BOF|x64 12 | Debug BOF|x86 = Debug BOF|x86 13 | Debug DLL|Any CPU = Debug DLL|Any CPU 14 | Debug DLL|x64 = Debug DLL|x64 15 | Debug DLL|x86 = Debug DLL|x86 16 | Debug|Any CPU = Debug|Any CPU 17 | Debug|x64 = Debug|x64 18 | Debug|x86 = Debug|x86 19 | Release BOF|Any CPU = Release BOF|Any CPU 20 | Release BOF|x64 = Release BOF|x64 21 | Release BOF|x86 = Release BOF|x86 22 | Release DLL|Any CPU = Release DLL|Any CPU 23 | Release DLL|x64 = Release DLL|x64 24 | Release DLL|x86 = Release DLL|x86 25 | Release|Any CPU = Release|Any CPU 26 | Release|x64 = Release|x64 27 | Release|x86 = Release|x86 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug BOF|Any CPU.ActiveCfg = Debug BOF|Any CPU 31 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug BOF|Any CPU.Build.0 = Debug BOF|Any CPU 32 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug BOF|x64.ActiveCfg = Debug BOF|x64 33 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug BOF|x64.Build.0 = Debug BOF|x64 34 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug BOF|x86.ActiveCfg = Debug BOF|x86 35 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug BOF|x86.Build.0 = Debug BOF|x86 36 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug DLL|Any CPU.ActiveCfg = Debug DLL|Any CPU 37 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug DLL|Any CPU.Build.0 = Debug DLL|Any CPU 38 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug DLL|x64.ActiveCfg = Debug DLL|Any CPU 39 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug DLL|x64.Build.0 = Debug DLL|Any CPU 40 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug DLL|x86.ActiveCfg = Debug DLL|Any CPU 41 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug DLL|x86.Build.0 = Debug DLL|Any CPU 42 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug|x64.ActiveCfg = Debug|x64 45 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug|x64.Build.0 = Debug|x64 46 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug|x86.ActiveCfg = Debug|x86 47 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Debug|x86.Build.0 = Debug|x86 48 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release BOF|Any CPU.ActiveCfg = Release BOF|Any CPU 49 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release BOF|Any CPU.Build.0 = Release BOF|Any CPU 50 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release BOF|x64.ActiveCfg = Release BOF|x64 51 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release BOF|x64.Build.0 = Release BOF|x64 52 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release BOF|x86.ActiveCfg = Release BOF|x86 53 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release BOF|x86.Build.0 = Release BOF|x86 54 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release DLL|Any CPU.ActiveCfg = Release DLL|Any CPU 55 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release DLL|Any CPU.Build.0 = Release DLL|Any CPU 56 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release DLL|x64.ActiveCfg = Release DLL|x64 57 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release DLL|x64.Build.0 = Release DLL|x64 58 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release DLL|x86.ActiveCfg = Release DLL|x86 59 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release DLL|x86.Build.0 = Release DLL|x86 60 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release|x64.ActiveCfg = Release|x64 63 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release|x64.Build.0 = Release|x64 64 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release|x86.ActiveCfg = Release|x86 65 | {555AD0AC-1FDB-4016-8257-170A74CB2F55}.Release|x86.Build.0 = Release|x86 66 | EndGlobalSection 67 | GlobalSection(SolutionProperties) = preSolution 68 | HideSolutionNode = FALSE 69 | EndGlobalSection 70 | GlobalSection(ExtensibilityGlobals) = postSolution 71 | SolutionGuid = {B3B5B4D8-74DD-4715-801C-1DC6DC1E2091} 72 | EndGlobalSection 73 | EndGlobal 74 | -------------------------------------------------------------------------------- /Source/NoPowerShell/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Arguments/Argument.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | /* 4 | Author: @bitsadmin 5 | Website: https://github.com/bitsadmin 6 | License: BSD 3-Clause 7 | */ 8 | 9 | namespace NoPowerShell.Arguments 10 | { 11 | /// 12 | /// Base class for BoolArgument and StringArgument 13 | /// 14 | public class Argument : IEquatable 15 | { 16 | /// 17 | /// Name of the argument, for example "-Path" 18 | /// 19 | protected string _name; 20 | protected bool _isOptionalArgument; 21 | protected bool _dashArgumentNameSkipUsed; 22 | 23 | public Argument(string name) 24 | { 25 | this._name = name; 26 | _dashArgumentNameSkipUsed = false; 27 | } 28 | 29 | public bool Equals(Argument other) 30 | { 31 | return other.Name.Equals(_name.Substring(0, other.Name.Length), StringComparison.InvariantCultureIgnoreCase); 32 | } 33 | 34 | public string Name 35 | { 36 | get { return _name; } 37 | } 38 | 39 | public bool IsOptionalArgument 40 | { 41 | get { return this._isOptionalArgument; } 42 | } 43 | 44 | /// 45 | /// Optional StringArgument which requires a value 46 | /// 47 | public bool DashArgumentNameSkipUsed 48 | { 49 | get { return _dashArgumentNameSkipUsed; } 50 | set { _dashArgumentNameSkipUsed = value; } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Arguments/ArgumentList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | /* 5 | Author: @bitsadmin 6 | Website: https://github.com/bitsadmin 7 | License: BSD 3-Clause 8 | */ 9 | 10 | namespace NoPowerShell.Arguments 11 | { 12 | public class ArgumentList : List 13 | { 14 | public T Get(string argumentName) where T : Argument 15 | { 16 | foreach (Argument arg in this) 17 | { 18 | // Skip irrelevant arguments 19 | if (arg.GetType() != typeof(T)) 20 | continue; 21 | 22 | // Check for matching argumentName 23 | T foundArg = arg as T; 24 | if (foundArg.Name.Equals(argumentName, StringComparison.InvariantCultureIgnoreCase)) 25 | return foundArg; 26 | } 27 | 28 | return null; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Arguments/BoolArgument.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Author: @bitsadmin 3 | Website: https://github.com/bitsadmin 4 | License: BSD 3-Clause 5 | */ 6 | 7 | namespace NoPowerShell.Arguments 8 | { 9 | public class BoolArgument : Argument 10 | { 11 | private bool _value; 12 | 13 | /// 14 | /// Create a new boolean argument including its default value. Bool arguments are always optional. 15 | /// 16 | /// Name of the parameter 17 | /// Default value of the argument 18 | public BoolArgument(string argumentName, bool defaultValue) : base(argumentName) 19 | { 20 | this._value = defaultValue; 21 | this._isOptionalArgument = true; 22 | } 23 | 24 | /// 25 | /// Create new boolean argument with false as its default value. Bool arguments are always optional. 26 | /// 27 | /// Name of the parameter 28 | public BoolArgument(string argumentName) : this(argumentName, false) 29 | { 30 | } 31 | 32 | public bool Value 33 | { 34 | get { return this._value; } 35 | set { this._value = value; } 36 | } 37 | 38 | public override string ToString() 39 | { 40 | return string.Format("{0}: {1}", _name, _value); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Arguments/IntegerArgument.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Author: @bitsadmin 3 | Website: https://github.com/bitsadmin 4 | License: BSD 3-Clause 5 | */ 6 | 7 | namespace NoPowerShell.Arguments 8 | { 9 | public class IntegerArgument : Argument 10 | { 11 | private int _value; 12 | private int _defaultValue; 13 | 14 | /// 15 | /// Create a new integer argument including its default value. 16 | /// 17 | /// Name of the parameter 18 | /// Default value of the argument 19 | public IntegerArgument(string argumentName, int defaultValue) : base(argumentName) 20 | { 21 | this._value = defaultValue; 22 | this._defaultValue = defaultValue; 23 | this._isOptionalArgument = false; 24 | } 25 | 26 | /// 27 | /// Create a new integer argument including its default value specifying whether it is optional or not. 28 | /// 29 | /// Name of the parameter 30 | /// Default value of the argument 31 | /// True if the argument is optional; False if not 32 | public IntegerArgument(string argumentName, int defaultValue, bool optionalArgument) : this(argumentName, defaultValue) 33 | { 34 | this._isOptionalArgument = optionalArgument; 35 | } 36 | 37 | /// 38 | /// Create a new integer argument with a null default value. 39 | /// 40 | /// Name of the parameter 41 | public IntegerArgument(string argumentName) : this(argumentName, 0) 42 | { 43 | } 44 | 45 | public int Value 46 | { 47 | get { return _value; } 48 | set { _value = value; } 49 | } 50 | 51 | public bool IsDefaultValue 52 | { 53 | get { return _value == _defaultValue; } 54 | } 55 | 56 | public override string ToString() 57 | { 58 | return string.Format("{0} \"{1}\"", _name, _value); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Arguments/StringArgument.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Author: @bitsadmin 3 | Website: https://github.com/bitsadmin 4 | License: BSD 3-Clause 5 | */ 6 | 7 | namespace NoPowerShell.Arguments 8 | { 9 | public class StringArgument : Argument 10 | { 11 | private string _value; 12 | private string _defaultValue; 13 | 14 | /// 15 | /// Create a new string argument including its default value. 16 | /// 17 | /// Name of the parameter 18 | /// Default value of the argument 19 | public StringArgument(string argumentName, string defaultValue) : base(argumentName) 20 | { 21 | this._value = defaultValue; 22 | this._defaultValue = defaultValue; 23 | this._isOptionalArgument = false; 24 | } 25 | 26 | /// 27 | /// Create a new string argument including its default value specifying whether it is optional or not. 28 | /// 29 | /// Name of the parameter 30 | /// Default value of the argument 31 | /// True if the argument is optional; False if not 32 | public StringArgument(string argumentName, string defaultValue, bool optionalArgument) : this(argumentName, defaultValue) 33 | { 34 | this._isOptionalArgument = optionalArgument; 35 | } 36 | 37 | /// 38 | /// Create a new string argument with a null default value specifying whether it is optional or not. 39 | /// 40 | /// Name of the parameter 41 | /// True if the argument is optional; False if not 42 | public StringArgument(string argumentName, bool optionalArgument) : this(argumentName, null, optionalArgument) 43 | { 44 | } 45 | 46 | /// 47 | /// Create a new string argument with a null default value. 48 | /// 49 | /// Name of the parameter 50 | public StringArgument(string argumentName) : this(argumentName, null) 51 | { 52 | } 53 | 54 | public string Value 55 | { 56 | get { return _value; } 57 | set { _value = value; } 58 | } 59 | 60 | public bool IsDefaultValue 61 | { 62 | get { return string.Equals(_value, _defaultValue, System.StringComparison.InvariantCultureIgnoreCase); } 63 | } 64 | 65 | public override string ToString() 66 | { 67 | return string.Format("{0} \"{1}\"", _name, _value); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/ActiveDirectory/GetADComputerCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.ActiveDirectory 13 | { 14 | public class GetADComputerCommand : PSCommand 15 | { 16 | public GetADComputerCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Obtain cmdlet parameters 23 | string server = _arguments.Get("Server").Value; 24 | string searchBase = _arguments.Get("SearchBase").Value; 25 | string identity = _arguments.Get("Identity").Value; 26 | string ldapFilter = _arguments.Get("LDAPFilter").Value; 27 | string filter = _arguments.Get("Filter").Value; 28 | string properties = _arguments.Get("Properties").Value; 29 | 30 | // Determine filters 31 | bool filledIdentity = !string.IsNullOrEmpty(identity); 32 | bool filledLdapFilter = !string.IsNullOrEmpty(ldapFilter); 33 | bool filledFilter = !string.IsNullOrEmpty(filter); 34 | 35 | // Input checks 36 | if (filledIdentity && filledLdapFilter) 37 | throw new NoPowerShellException("Specify either Identity or LDAPFilter, not both"); 38 | if (!filledIdentity && !filledLdapFilter && !filledFilter) 39 | throw new NoPowerShellException("Specify either Identity, Filter or LDAPFilter"); 40 | 41 | // Build filter 42 | string filterBase = "(&(objectCategory=computer){0})"; 43 | string queryFilter = string.Empty; 44 | 45 | // -Identity DC01 46 | if (filledIdentity) 47 | queryFilter = string.Format(filterBase, string.Format("(cn={0})", identity)); 48 | 49 | // -LDAPFilter "(msDFSR-ComputerReferenceBL=*)" 50 | else if (filledLdapFilter) 51 | { 52 | queryFilter = string.Format(filterBase, ldapFilter); 53 | } 54 | 55 | // -Filter * 56 | else if (filledFilter) 57 | { 58 | // TODO: allow more types of filters 59 | if (filter != "*") 60 | throw new NoPowerShellException("Currently only * filter is supported"); 61 | 62 | queryFilter = string.Format(filterBase, string.Empty); 63 | } 64 | 65 | // Query 66 | _results = LDAPHelper.QueryLDAP(searchBase, queryFilter, new List(properties.Split(',')), server, username, password); 67 | 68 | return _results; 69 | } 70 | 71 | public static new CaseInsensitiveList Aliases 72 | { 73 | get { return new CaseInsensitiveList() { "Get-ADComputer" }; } 74 | } 75 | 76 | public static new ArgumentList SupportedArguments 77 | { 78 | get 79 | { 80 | return new ArgumentList() 81 | { 82 | new StringArgument("Server", true), 83 | new StringArgument("SearchBase", true), 84 | new StringArgument("Identity"), 85 | new StringArgument("Filter", true), 86 | new StringArgument("LDAPFilter", true), 87 | new StringArgument("Properties", "DistinguishedName,DNSHostName,Name,ObjectClass,ObjectGUID,SamAccountName,ObjectSID,UserPrincipalName", true) 88 | }; 89 | } 90 | } 91 | 92 | public static new string Synopsis 93 | { 94 | get { return "Gets one or more Active Directory computers."; } 95 | } 96 | 97 | public static new ExampleEntries Examples 98 | { 99 | get 100 | { 101 | return new ExampleEntries() 102 | { 103 | new ExampleEntry("List all properties of the DC01 domain computer", "Get-ADComputer -Identity DC01 -Properties *"), 104 | new ExampleEntry("List all Domain Controllers", "Get-ADComputer -LDAPFilter \"(msDFSR-ComputerReferenceBL=*)\""), 105 | new ExampleEntry("List all computers in domain", "Get-ADComputer -Filter *"), 106 | new ExampleEntry("List domain controllers", "Get-ADComputer -searchBase \"OU=Domain Controllers,DC=bitsadmin,DC=local\" -Filter *"), 107 | new ExampleEntry("List specific attributes of the DC01 domain computer", "Get-ADComputer DC01 -Properties Name,operatingSystem") 108 | }; 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/ActiveDirectory/GetADGroupCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.ActiveDirectory 13 | { 14 | public class GetADGroupCommand : PSCommand 15 | { 16 | public GetADGroupCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Obtain cmdlet parameters 23 | string server = _arguments.Get("Server").Value; 24 | string searchBase = _arguments.Get("SearchBase").Value; 25 | string identity = _arguments.Get("Identity").Value; 26 | string ldapFilter = _arguments.Get("LDAPFilter").Value; 27 | string filter = _arguments.Get("Filter").Value; 28 | string properties = _arguments.Get("Properties").Value; 29 | 30 | // Determine filters 31 | bool filledIdentity = !string.IsNullOrEmpty(identity); 32 | bool filledLdapFilter = !string.IsNullOrEmpty(ldapFilter); 33 | bool filledFilter = !string.IsNullOrEmpty(filter); 34 | 35 | // Input checks 36 | if (filledIdentity && filledLdapFilter) 37 | throw new NoPowerShellException("Specify either Identity or LDAPFilter, not both"); 38 | if (!filledIdentity && !filledLdapFilter && !filledFilter) 39 | throw new NoPowerShellException("Specify either Identity, Filter or LDAPFilter"); 40 | 41 | // Build filter 42 | string filterBase = "(&(objectCategory=group){0})"; 43 | string queryFilter = string.Empty; 44 | 45 | // -Identity Administrator 46 | if (filledIdentity) 47 | { 48 | queryFilter = string.Format(filterBase, string.Format("(sAMAccountName={0})", identity)); 49 | } 50 | 51 | // -LDAPFilter "(adminCount=1)" 52 | else if (filledLdapFilter) 53 | { 54 | queryFilter = string.Format(filterBase, ldapFilter); 55 | } 56 | 57 | // -Filter * 58 | else if (filledFilter) 59 | { 60 | // TODO: allow more types of filters 61 | if (filter != "*") 62 | throw new NoPowerShellException("Currently only * filter is supported"); 63 | 64 | queryFilter = string.Format(filterBase, string.Empty); 65 | } 66 | 67 | // Query 68 | _results = LDAPHelper.QueryLDAP(searchBase, queryFilter, new List(properties.Split(',')), server, username, password); 69 | 70 | return _results; 71 | } 72 | 73 | public static new CaseInsensitiveList Aliases 74 | { 75 | get { return new CaseInsensitiveList() { "Get-ADGroup" }; } 76 | } 77 | 78 | public static new ArgumentList SupportedArguments 79 | { 80 | get 81 | { 82 | return new ArgumentList() 83 | { 84 | new StringArgument("Server", true), 85 | new StringArgument("SearchBase", true), 86 | new StringArgument("Identity"), 87 | new StringArgument("Filter"), 88 | new StringArgument("LDAPFilter"), 89 | new StringArgument("Properties", "DistinguishedName,Name,ObjectClass,ObjectGUID,SamAccountName,ObjectSID", true) 90 | }; 91 | } 92 | } 93 | 94 | public static new string Synopsis 95 | { 96 | get { return "Gets one or more Active Directory groups."; } 97 | } 98 | 99 | public static new ExampleEntries Examples 100 | { 101 | get 102 | { 103 | return new ExampleEntries() 104 | { 105 | new ExampleEntry("List all user groups in domain", "Get-ADGroup -Filter *"), 106 | new ExampleEntry("List all administrative groups in domain", "Get-ADGroup -LDAPFilter \"(admincount=1)\" | select Name") 107 | }; 108 | } 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/ActiveDirectory/GetADGroupMemberCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.ActiveDirectory 12 | { 13 | public class GetADGroupMemberCommand : PSCommand 14 | { 15 | public GetADGroupMemberCommand(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | // Obtain cmdlet parameters 22 | string server = _arguments.Get("Server").Value; 23 | string identity = _arguments.Get("Identity").Value; 24 | 25 | // Obtain distinguishedname for group 26 | CommandResult dn = LDAPHelper.QueryLDAP( 27 | string.Format("(&(objectCategory=group)(cn={0}))", identity), 28 | new List(1) { "distinguishedName" } 29 | ); 30 | string distinguishedName = dn[0]["distinguishedName"]; 31 | 32 | _results = LDAPHelper.QueryLDAP( 33 | null, 34 | string.Format("(memberOf={0})", distinguishedName), 35 | new List(1) { "distinguishedName", "name", "objectClass", "objectGUID", "SamAccountName", "SID" }, 36 | server, 37 | username, 38 | password 39 | ); 40 | 41 | return _results; 42 | } 43 | 44 | public static new CaseInsensitiveList Aliases 45 | { 46 | get { return new CaseInsensitiveList() { "Get-ADGroupMember" }; } 47 | } 48 | 49 | public static new ArgumentList SupportedArguments 50 | { 51 | get 52 | { 53 | return new ArgumentList() 54 | { 55 | new StringArgument("Server", true), 56 | new StringArgument("Identity") 57 | }; 58 | } 59 | } 60 | 61 | public static new string Synopsis 62 | { 63 | get { return "Gets the members of an Active Directory group."; } 64 | } 65 | 66 | public static new ExampleEntries Examples 67 | { 68 | get 69 | { 70 | return new ExampleEntries() 71 | { 72 | new ExampleEntry 73 | ( 74 | "List all members of the \"Domain Admins\" group", 75 | new List() 76 | { 77 | "Get-ADGroupMember -Identity \"Domain Admins\"", 78 | "Get-ADGroupMember \"Domain Admins\"" 79 | } 80 | ) 81 | }; 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/ActiveDirectory/GetADObjectCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.DirectoryServices; 6 | 7 | /* 8 | Author: @bitsadmin 9 | Website: https://github.com/bitsadmin 10 | License: BSD 3-Clause 11 | */ 12 | 13 | namespace NoPowerShell.Commands.ActiveDirectory 14 | { 15 | public class GetADObjectCommand : PSCommand 16 | { 17 | public GetADObjectCommand(string[] userArguments) : base(userArguments, SupportedArguments) 18 | { 19 | } 20 | 21 | public override CommandResult Execute(CommandResult pipeIn) 22 | { 23 | // Obtain cmdlet parameters 24 | string server = _arguments.Get("Server").Value; 25 | string searchBase = _arguments.Get("SearchBase").Value; 26 | string identity = _arguments.Get("Identity").Value; 27 | string ldapFilter = _arguments.Get("LDAPFilter").Value; 28 | List properties = new List(_arguments.Get("Properties").Value.Split(',')); 29 | 30 | // Input check 31 | SearchScope scope; 32 | if (string.IsNullOrEmpty(ldapFilter)) 33 | { 34 | // Neither LDAPFilter nor Identity specified 35 | if (string.IsNullOrEmpty(identity)) 36 | throw new NoPowerShellException("Either LDAPFilter or Identity parameter is required"); 37 | // Identity is specified, so search on the base 38 | else 39 | { 40 | searchBase = identity; 41 | scope = SearchScope.Base; 42 | } 43 | } 44 | // LDAPFilter is specified 45 | else 46 | scope = SearchScope.Subtree; 47 | 48 | // Query 49 | _results = LDAPHelper.QueryLDAP(searchBase, scope, ldapFilter, properties, server, username, password); 50 | 51 | return _results; 52 | } 53 | 54 | public static new CaseInsensitiveList Aliases 55 | { 56 | get { return new CaseInsensitiveList() { "Get-ADObject" }; } 57 | } 58 | 59 | public static new ArgumentList SupportedArguments 60 | { 61 | get 62 | { 63 | return new ArgumentList() 64 | { 65 | new StringArgument("Server", true), 66 | new StringArgument("SearchBase"), 67 | new StringArgument("Identity"), 68 | new StringArgument("LDAPFilter"), 69 | new StringArgument("Properties", "DistinguishedName,Name,ObjectClass,ObjectGUID", true) 70 | }; 71 | } 72 | } 73 | 74 | public static new string Synopsis 75 | { 76 | get { return "Gets one or more Active Directory objects."; } 77 | } 78 | 79 | public static new ExampleEntries Examples 80 | { 81 | get 82 | { 83 | return new ExampleEntries() 84 | { 85 | new ExampleEntry("Get the sites from the configuration naming context", "Get-ADObject -LDAPFilter \"(objectClass=site)\" -SearchBase \"CN=Configuration,DC=MyDomain,DC=local\" -Properties whenCreated,cn"), 86 | new ExampleEntry("Get specific object", "Get-ADObject -Identity \"CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=MyDomain,DC=local\" -Properties *"), 87 | new ExampleEntry("List all global groups", "Get-ADObject –LDAPFilter \"(GroupType:1.2.840.113556.1.4.803:=2)\" –SearchBase \"DC=MyDomain,DC=local\"") 88 | }; 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/ActiveDirectory/GetADUserCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.ActiveDirectory 13 | { 14 | public class GetADUserCommand : PSCommand 15 | { 16 | public GetADUserCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Obtain cmdlet parameters 23 | string server = _arguments.Get("Server").Value; 24 | string searchBase = _arguments.Get("SearchBase").Value; 25 | string identity = _arguments.Get("Identity").Value; 26 | string ldapFilter = _arguments.Get("LDAPFilter").Value; 27 | string filter = _arguments.Get("Filter").Value; 28 | CaseInsensitiveList properties = new CaseInsensitiveList(_arguments.Get("Properties").Value.Split(',')); 29 | 30 | // Determine filters 31 | bool filledIdentity = !string.IsNullOrEmpty(identity); 32 | bool filledLdapFilter = !string.IsNullOrEmpty(ldapFilter); 33 | bool filledFilter = !string.IsNullOrEmpty(filter); 34 | 35 | // Input checks 36 | if (filledIdentity && filledLdapFilter) 37 | throw new NoPowerShellException("Specify either Identity or LDAPFilter, not both"); 38 | if (!filledIdentity && !filledLdapFilter && !filledFilter) 39 | throw new NoPowerShellException("Specify either Identity, Filter or LDAPFilter"); 40 | 41 | // Build filter 42 | string filterBase = "(&(objectCategory=user){0})"; 43 | string queryFilter = string.Empty; 44 | 45 | // -Identity Administrator 46 | if (filledIdentity) 47 | queryFilter = string.Format(filterBase, string.Format("(sAMAccountName={0})", identity)); 48 | 49 | // -LDAPFilter "(adminCount=1)" 50 | else if (filledLdapFilter) 51 | { 52 | queryFilter = string.Format(filterBase, ldapFilter); 53 | } 54 | 55 | // -Filter * 56 | else if (filledFilter) 57 | { 58 | // TODO: allow more types of filters 59 | if (filter != "*") 60 | throw new NoPowerShellException("Currently only * filter is supported"); 61 | 62 | queryFilter = string.Format(filterBase, string.Empty); 63 | } 64 | 65 | // Query 66 | _results = LDAPHelper.QueryLDAP(searchBase, queryFilter, properties, server, username, password); 67 | 68 | // Translate UserAccountControl AD field into whether the account is enabled 69 | if (_results.Count > 0 && _results[0].ContainsKey("useraccountcontrol")) 70 | { 71 | foreach (ResultRecord r in _results) 72 | { 73 | string uac = r["useraccountcontrol"]; 74 | bool active = LDAPHelper.IsActive(uac); 75 | r["Enabled"] = active.ToString(); 76 | //r.Remove("useraccountcontrol"); 77 | } 78 | } 79 | 80 | return _results; 81 | } 82 | 83 | public static new CaseInsensitiveList Aliases 84 | { 85 | get { return new CaseInsensitiveList() { "Get-ADUser" }; } 86 | } 87 | 88 | public static new ArgumentList SupportedArguments 89 | { 90 | get 91 | { 92 | return new ArgumentList() 93 | { 94 | new StringArgument("Server", true), 95 | new StringArgument("SearchBase", true), 96 | new StringArgument("Identity"), 97 | new StringArgument("Filter", true), 98 | new StringArgument("LDAPFilter", true), 99 | new StringArgument("Properties", "DistinguishedName,userAccountControl,GivenName,Name,ObjectClass,ObjectGUID,SamAccountName,ObjectSID,Surname,UserPrincipalName", true) 100 | }; 101 | } 102 | } 103 | 104 | public static new string Synopsis 105 | { 106 | get { return "Gets one or more Active Directory users."; } 107 | } 108 | 109 | public static new ExampleEntries Examples 110 | { 111 | get 112 | { 113 | return new ExampleEntries() 114 | { 115 | new ExampleEntry("List all properties of the Administrator domain user", "Get-ADUser -Identity Administrator -Properties *"), 116 | new ExampleEntry("List all Administrative users in domain", "Get-ADUser -LDAPFilter \"(admincount=1)\""), 117 | new ExampleEntry("List all users in domain", "Get-ADUser -Filter *"), 118 | new ExampleEntry("List specific attributes of user", "Get-ADUser Administrator -Properties SamAccountName,ObjectSID"), 119 | new ExampleEntry("List all users in a specific OU", "Get-ADUser -SearchBase \"CN=Users,DC=MyDomain,DC=local\" -Filter *") 120 | }; 121 | } 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Additional/GetRemoteSmbShareCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | 8 | /* 9 | Author: @bitsadmin 10 | Website: https://github.com/bitsadmin 11 | License: BSD 3-Clause 12 | */ 13 | 14 | namespace NoPowerShell.Commands.Additional 15 | { 16 | public class GetRemoteSmbShareCommand : PSCommand 17 | { 18 | public GetRemoteSmbShareCommand(string[] arguments) : base(arguments, SupportedArguments) 19 | { 20 | } 21 | 22 | public override CommandResult Execute(CommandResult pipeIn) 23 | { 24 | string server = _arguments.Get("Server").Value; 25 | 26 | if (string.IsNullOrEmpty(server)) 27 | throw new NoPowerShellException("Mandatory -Server argument missing"); 28 | 29 | server = server.Replace(@"\\", ""); 30 | 31 | GetNetShares gns = new GetNetShares(); 32 | GetNetShares.SHARE_INFO_1[] shares = gns.EnumNetShares(server); 33 | 34 | foreach(GetNetShares.SHARE_INFO_1 share in shares) 35 | { 36 | _results.Add( 37 | new ResultRecord() 38 | { 39 | { "Name", share.shi1_netname }, 40 | { "Description", share.shi1_remark } 41 | //{ "Type", share.shi1_type.ToString() } 42 | } 43 | ); 44 | } 45 | 46 | return _results; 47 | } 48 | 49 | // Source: https://www.pinvoke.net/default.aspx/netapi32/netshareenum.html 50 | public class GetNetShares 51 | { 52 | #region External Calls 53 | [DllImport("Netapi32.dll", SetLastError = true)] 54 | static extern int NetApiBufferFree(IntPtr Buffer); 55 | [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)] 56 | private static extern int NetShareEnum( 57 | StringBuilder ServerName, 58 | int level, 59 | ref IntPtr bufPtr, 60 | uint prefmaxlen, 61 | ref int entriesread, 62 | ref int totalentries, 63 | ref int resume_handle 64 | ); 65 | #endregion 66 | #region External Structures 67 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 68 | public struct SHARE_INFO_1 69 | { 70 | public string shi1_netname; 71 | public uint shi1_type; 72 | public string shi1_remark; 73 | public SHARE_INFO_1(string sharename, uint sharetype, string remark) 74 | { 75 | this.shi1_netname = sharename; 76 | this.shi1_type = sharetype; 77 | this.shi1_remark = remark; 78 | } 79 | public override string ToString() 80 | { 81 | return shi1_netname; 82 | } 83 | } 84 | #endregion 85 | const uint MAX_PREFERRED_LENGTH = 0xFFFFFFFF; 86 | const int NERR_Success = 0; 87 | private enum NetError : uint 88 | { 89 | NERR_Success = 0, 90 | NERR_BASE = 2100, 91 | NERR_UnknownDevDir = (NERR_BASE + 16), 92 | NERR_DuplicateShare = (NERR_BASE + 18), 93 | NERR_BufTooSmall = (NERR_BASE + 23), 94 | } 95 | private enum SHARE_TYPE : uint 96 | { 97 | STYPE_DISKTREE = 0, 98 | STYPE_PRINTQ = 1, 99 | STYPE_DEVICE = 2, 100 | STYPE_IPC = 3, 101 | STYPE_SPECIAL = 0x80000000, 102 | } 103 | public SHARE_INFO_1[] EnumNetShares(string Server) 104 | { 105 | List ShareInfos = new List(); 106 | int entriesread = 0; 107 | int totalentries = 0; 108 | int resume_handle = 0; 109 | int nStructSize = Marshal.SizeOf(typeof(SHARE_INFO_1)); 110 | IntPtr bufPtr = IntPtr.Zero; 111 | StringBuilder server = new StringBuilder(Server); 112 | int ret = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle); 113 | if (ret == NERR_Success) 114 | { 115 | IntPtr currentPtr = bufPtr; 116 | for (int i = 0; i < entriesread; i++) 117 | { 118 | SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1)); 119 | ShareInfos.Add(shi1); 120 | currentPtr = new IntPtr(currentPtr.ToInt64() + nStructSize); // Updated to support .NET 2.0 121 | } 122 | NetApiBufferFree(bufPtr); 123 | return ShareInfos.ToArray(); 124 | } 125 | else 126 | { 127 | ShareInfos.Add(new SHARE_INFO_1("ERROR=" + ret.ToString(), 10, string.Empty)); 128 | return ShareInfos.ToArray(); 129 | } 130 | } 131 | } 132 | 133 | public static new CaseInsensitiveList Aliases 134 | { 135 | get { return new CaseInsensitiveList() { "Get-RemoteSmbShare", "netview" }; } 136 | } 137 | 138 | public static new ArgumentList SupportedArguments 139 | { 140 | get 141 | { 142 | return new ArgumentList() 143 | { 144 | new StringArgument("Server") 145 | }; 146 | } 147 | } 148 | 149 | public static new string Synopsis 150 | { 151 | get { return "Retrieves the SMB shares of a computer."; } 152 | } 153 | 154 | public static new ExampleEntries Examples 155 | { 156 | get 157 | { 158 | return new ExampleEntries() 159 | { 160 | new ExampleEntry("List SMB shares of MyServer", "Get-RemoteSmbShare \\\\MyServer") 161 | }; 162 | } 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Additional/GetWhoamiCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | 4 | /* 5 | Author: @bitsadmin 6 | Website: https://github.com/bitsadmin 7 | License: BSD 3-Clause 8 | */ 9 | 10 | namespace NoPowerShell.Commands.Additional 11 | { 12 | public class GetWhoamiCommand : PSCommand 13 | { 14 | public GetWhoamiCommand(string[] arguments) : base(arguments, SupportedArguments) 15 | { 16 | } 17 | 18 | public override CommandResult Execute(CommandResult pipeIn) 19 | { 20 | bool showAll = _arguments.Get("All").Value; 21 | 22 | string[] DomainUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\'); 23 | 24 | _results.Add( 25 | new ResultRecord() 26 | { 27 | { "Domain", DomainUser[0] }, 28 | { "User", DomainUser[1] } 29 | } 30 | ); 31 | 32 | if(showAll) 33 | { 34 | // TODO 35 | } 36 | 37 | return _results; 38 | } 39 | 40 | public static new CaseInsensitiveList Aliases 41 | { 42 | get { return new CaseInsensitiveList() { "Get-Whoami", "whoami" }; } 43 | } 44 | 45 | public static new ArgumentList SupportedArguments 46 | { 47 | get 48 | { 49 | return new ArgumentList() 50 | { 51 | new BoolArgument("All") 52 | }; 53 | } 54 | } 55 | 56 | public static new string Synopsis 57 | { 58 | get { return "Show details about the current user."; } 59 | } 60 | 61 | public static new ExampleEntries Examples 62 | { 63 | get 64 | { 65 | return new ExampleEntries() 66 | { 67 | new ExampleEntry("Show the current user", "whoami") 68 | }; 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Archive/CompressArchiveCommand.cs: -------------------------------------------------------------------------------- 1 | #if MAJOR1 || MAJOR2 || MAJOR3 || (MAJOR4 && MINOR0) 2 | #warning Compress-Archive requires at least .NET 4.5 3 | #else 4 | using NoPowerShell.Arguments; 5 | using NoPowerShell.HelperClasses; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.IO.Compression; 10 | 11 | /* 12 | Author: @bitsadmin 13 | Website: https://github.com/bitsadmin 14 | License: BSD 3-Clause 15 | */ 16 | 17 | namespace NoPowerShell.Commands.Archive 18 | { 19 | public class CompressArchiveCommand : PSCommand 20 | { 21 | public CompressArchiveCommand(string[] userArguments) : base(userArguments, SupportedArguments) 22 | { 23 | } 24 | 25 | public override CommandResult Execute(CommandResult pipeIn) 26 | { 27 | // Obtain cmdlet parameters 28 | string path = _arguments.Get("Path").Value; 29 | string destinationPath = _arguments.Get("DestinationPath").Value; 30 | string compressionLevel = _arguments.Get("CompressionLevel").Value; 31 | CompressionLevel cl = CompressionLevel.Optimal; 32 | 33 | // Determine compression level 34 | switch (compressionLevel.ToLowerInvariant()) 35 | { 36 | case "optimal": 37 | cl = CompressionLevel.Optimal; 38 | break; 39 | case "nocompression": 40 | cl = CompressionLevel.NoCompression; 41 | break; 42 | case "fastest": 43 | cl = CompressionLevel.Fastest; 44 | break; 45 | default: 46 | throw new ArgumentException(string.Format("Unknown compression level: {0}. Possible options: Optimal, NoCompression, Fastest.", compressionLevel)); 47 | } 48 | 49 | // Determine whether input is file or directory 50 | FileAttributes attr = File.GetAttributes(path); 51 | 52 | // Compress directory 53 | if ((attr & FileAttributes.Directory) == FileAttributes.Directory) 54 | { 55 | ZipFile.CreateFromDirectory(path, destinationPath, cl, false); 56 | } 57 | 58 | // Compress file 59 | else 60 | { 61 | FileInfo fi = new FileInfo(path); 62 | 63 | using (FileStream fs = new FileStream(destinationPath, FileMode.Create)) 64 | using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create)) 65 | { 66 | arch.CreateEntryFromFile(path, fi.Name); 67 | } 68 | } 69 | 70 | // Return resulting filename 71 | _results.Add( 72 | new ResultRecord() 73 | { 74 | { "Path", destinationPath } 75 | } 76 | ); 77 | return _results; 78 | } 79 | 80 | public static new CaseInsensitiveList Aliases 81 | { 82 | get 83 | { 84 | return new CaseInsensitiveList() 85 | { 86 | "Compress-Archive", 87 | "zip" // Unofficial 88 | }; 89 | } 90 | } 91 | 92 | public static new ArgumentList SupportedArguments 93 | { 94 | get 95 | { 96 | return new ArgumentList() 97 | { 98 | new StringArgument("Path"), 99 | new StringArgument("DestinationPath"), 100 | new StringArgument("CompressionLevel", "Optimal") 101 | }; 102 | } 103 | } 104 | 105 | public static new string Synopsis 106 | { 107 | get { return "Creates an archive, or zipped file, from specified files and folders."; } 108 | } 109 | 110 | public static new ExampleEntries Examples 111 | { 112 | get 113 | { 114 | return new ExampleEntries() 115 | { 116 | new ExampleEntry 117 | ( 118 | "Compress folder to zip", 119 | new List() 120 | { 121 | "Compress-Archive -Path C:\\MyFolder -DestinationPath C:\\MyFolder.zip", 122 | "zip C:\\MyFolder C:\\MyFolder.zip" 123 | } 124 | ) 125 | }; 126 | } 127 | } 128 | } 129 | } 130 | #endif -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Archive/ExpandArchiveCommand.cs: -------------------------------------------------------------------------------- 1 | #if MAJOR1 || MAJOR2 || MAJOR3 || (MAJOR4 && MINOR0) 2 | #warning Expand-Archive requires at least .NET 4.5 3 | #else 4 | using NoPowerShell.Arguments; 5 | using NoPowerShell.HelperClasses; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.IO.Compression; 9 | 10 | /* 11 | Author: @bitsadmin 12 | Website: https://github.com/bitsadmin 13 | License: BSD 3-Clause 14 | */ 15 | 16 | namespace NoPowerShell.Commands.Archive 17 | { 18 | public class ExpandArchiveCommand : PSCommand 19 | { 20 | public ExpandArchiveCommand(string[] userArguments) : base(userArguments, SupportedArguments) 21 | { 22 | } 23 | 24 | public override CommandResult Execute(CommandResult pipeIn) 25 | { 26 | // Obtain cmdlet parameters 27 | string path = _arguments.Get("Path").Value; 28 | string destinationPath = _arguments.Get("DestinationPath").Value; 29 | 30 | // Validate path 31 | if (!File.Exists(path)) 32 | throw new ItemNotFoundException(path); 33 | 34 | // Determine destination path if not specified 35 | if (string.IsNullOrEmpty(destinationPath)) 36 | destinationPath = Path.GetFullPath(Path.Combine(".\\", Path.GetFileNameWithoutExtension(path))); 37 | 38 | // Extract 39 | ZipFile.ExtractToDirectory(path, destinationPath); 40 | 41 | // Return resulting filename 42 | _results.Add( 43 | new ResultRecord() 44 | { 45 | { "Path", destinationPath } 46 | } 47 | ); 48 | return _results; 49 | } 50 | 51 | public static new CaseInsensitiveList Aliases 52 | { 53 | get 54 | { 55 | return new CaseInsensitiveList() 56 | { 57 | "Expand-Archive", 58 | "unzip" // Unofficial 59 | }; 60 | } 61 | } 62 | 63 | public static new ArgumentList SupportedArguments 64 | { 65 | get 66 | { 67 | return new ArgumentList() 68 | { 69 | new StringArgument("Path"), 70 | new StringArgument("DestinationPath") 71 | }; 72 | } 73 | } 74 | 75 | public static new string Synopsis 76 | { 77 | get { return "Extracts files from a specified archive (zipped) file."; } 78 | } 79 | 80 | public static new ExampleEntries Examples 81 | { 82 | get 83 | { 84 | return new ExampleEntries() 85 | { 86 | new ExampleEntry 87 | ( 88 | "Extract zip", 89 | new List() 90 | { 91 | "Expand-Archive -Path C:\\MyArchive.zip -DestinationPath C:\\Extracted", 92 | "unzip C:\\MyArchive.zip C:\\Extracted" 93 | } 94 | ), 95 | new ExampleEntry("Extract zip into current directory", "unzip C:\\MyArchive.zip"), 96 | }; 97 | } 98 | } 99 | } 100 | } 101 | #endif -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Core/GetHelpCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | using System.Text; 7 | 8 | /* 9 | Author: @bitsadmin 10 | Website: https://github.com/bitsadmin 11 | License: BSD 3-Clause 12 | */ 13 | 14 | namespace NoPowerShell.Commands.Core 15 | { 16 | public class GetHelpCommand : PSCommand 17 | { 18 | public GetHelpCommand(string[] userArguments) : base(userArguments, SupportedArguments) 19 | { 20 | } 21 | 22 | public override CommandResult Execute(CommandResult pipeIn) 23 | { 24 | // Obtain cmdlet parameters 25 | string name = _arguments.Get("Name").Value; 26 | 27 | // Show help for Get-Help if no name parameter is provided 28 | Type command = typeof(GetHelpCommand); 29 | 30 | // Determine command 31 | if (!string.IsNullOrEmpty(name)) 32 | { 33 | Dictionary commandTypes = ReflectionHelper.GetCommands(); 34 | bool found = false; 35 | foreach (KeyValuePair type in commandTypes) 36 | { 37 | if (type.Value.Contains(name)) 38 | { 39 | command = type.Key; 40 | found = true; 41 | break; 42 | } 43 | } 44 | 45 | if (!found) 46 | throw new NoPowerShellException(string.Format("Command {0} not found", name)); 47 | } 48 | 49 | // Collect information 50 | // Aliases 51 | PropertyInfo aliasesProperty = command.GetProperty("Aliases", BindingFlags.Static | BindingFlags.Public); 52 | CaseInsensitiveList aliases = (aliasesProperty != null) ? (CaseInsensitiveList)aliasesProperty.GetValue(null, null) : null; 53 | 54 | // SupportedArguments 55 | PropertyInfo argumentsProperty = command.GetProperty("SupportedArguments", BindingFlags.Static | BindingFlags.Public); 56 | ArgumentList supportedArguments = (argumentsProperty != null) ? (ArgumentList)argumentsProperty.GetValue(null, null) : null; 57 | 58 | // Hide internal parameters 59 | ArgumentList newarguments = new ArgumentList(); 60 | foreach (Argument arg in supportedArguments) 61 | { 62 | if (!arg.Name.StartsWith("_")) 63 | newarguments.Add(arg); 64 | } 65 | supportedArguments = newarguments; 66 | 67 | // Synopsis 68 | PropertyInfo synopsisProperty = command.GetProperty("Synopsis", BindingFlags.Static | BindingFlags.Public); 69 | string synopsis = (synopsisProperty != null) ? (string)synopsisProperty.GetValue(null, null) : null; 70 | 71 | // Examples 72 | PropertyInfo examplesProperty = command.GetProperty("Examples", BindingFlags.Static | BindingFlags.Public); 73 | ExampleEntries examples = (examplesProperty != null) ? (ExampleEntries)examplesProperty.GetValue(null, null) : null; 74 | 75 | // Compile man page 76 | string format = 77 | @"NAME 78 | {0} 79 | 80 | 81 | ALIASES 82 | {1} 83 | 84 | 85 | SYNOPSIS 86 | {2} 87 | 88 | 89 | SYNTAX 90 | {3} 91 | 92 | 93 | EXAMPLES 94 | {4} 95 | "; 96 | 97 | string commandName = (aliases != null) ? aliases[0] : null; 98 | string strAliases = string.Join(", ", aliases.GetRange(1, aliases.Count - 1).ToArray()); 99 | string arguments = string.Format("{0} {1}", aliases[0], GetCommandCommand.GetArguments(supportedArguments)); 100 | 101 | StringBuilder strExamples = new StringBuilder(); 102 | if (examples != null) 103 | { 104 | int exampleId = 1; 105 | foreach (ExampleEntry helpEntry in examples) 106 | { 107 | strExamples.AppendFormat(" --------------------- EXAMPLE {0} ---------------------\r\n\r\n", exampleId); 108 | strExamples.AppendFormat(" Synopsis: {0}\r\n\r\n", helpEntry.Description); 109 | foreach (string ex in helpEntry.Examples) 110 | { 111 | strExamples.AppendFormat(" C:\\> {0}\r\n\r\n", ex); 112 | } 113 | strExamples.AppendLine(); 114 | exampleId++; 115 | } 116 | } 117 | 118 | _results.Add( 119 | new ResultRecord() 120 | { 121 | { string.Empty, string.Format(format, commandName, strAliases, synopsis, arguments, strExamples.ToString()) } 122 | } 123 | ); 124 | 125 | return _results; 126 | } 127 | 128 | public static new CaseInsensitiveList Aliases 129 | { 130 | get { return new CaseInsensitiveList() { "Get-Help", "man" }; } 131 | } 132 | 133 | public static new ArgumentList SupportedArguments 134 | { 135 | get 136 | { 137 | return new ArgumentList() 138 | { 139 | new StringArgument("Name") 140 | }; 141 | } 142 | } 143 | 144 | public static new string Synopsis 145 | { 146 | get { return "Displays information about NoPowerShell commands."; } 147 | } 148 | 149 | public static new ExampleEntries Examples 150 | { 151 | get 152 | { 153 | return new ExampleEntries() 154 | { 155 | new ExampleEntry 156 | ( 157 | "Get help for a command", 158 | new List() 159 | { 160 | "Get-Help -Name Get-Process", 161 | "man ps" 162 | } 163 | ) 164 | }; 165 | } 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Core/WhereObjectCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | 4 | /* 5 | Author: @bitsadmin 6 | Website: https://github.com/bitsadmin 7 | License: BSD 3-Clause 8 | */ 9 | 10 | namespace NoPowerShell.Commands.Core 11 | { 12 | public class WhereObjectCommand : PSCommand 13 | { 14 | public WhereObjectCommand(string[] arguments) : base(arguments, SupportedArguments) 15 | { 16 | } 17 | 18 | public override CommandResult Execute(CommandResult pipeIn) 19 | { 20 | // Obtain parameters 21 | string property = _arguments.Get("Property").Value; 22 | bool eq = _arguments.Get("EQ").Value; 23 | bool ne = _arguments.Get("NE").Value; 24 | bool like = _arguments.Get("Like").Value; 25 | string value = _arguments.Get("Value").Value; 26 | 27 | // Iterate over output lines of previous command in pipe 28 | foreach (ResultRecord result in pipeIn) 29 | { 30 | // In case property does not exist, skip 31 | if (!result.ContainsKey(property)) 32 | continue; 33 | 34 | string tablevalue = result[property].ToLowerInvariant(); 35 | string checkvalue = value.ToLowerInvariant(); 36 | string cleancheckvalue = checkvalue.TrimStart('*').TrimEnd('*'); 37 | bool foundValue = false; 38 | 39 | // Name -eq "value" 40 | if (eq) 41 | { 42 | foundValue = (tablevalue == checkvalue); 43 | } 44 | // Name -ne "value" 45 | else if (ne) 46 | { 47 | foundValue = (tablevalue != checkvalue); 48 | } 49 | // Name -like "value" 50 | else if (like) 51 | { 52 | if (checkvalue.StartsWith("*")) 53 | { 54 | // - *value* 55 | if (checkvalue.EndsWith("*")) 56 | foundValue = tablevalue.Contains(cleancheckvalue); 57 | // - *value 58 | else 59 | foundValue = tablevalue.EndsWith(cleancheckvalue); 60 | } 61 | else 62 | { 63 | // - value* 64 | if (checkvalue.EndsWith("*")) 65 | foundValue = tablevalue.StartsWith(cleancheckvalue); 66 | // - value 67 | else 68 | foundValue = tablevalue == cleancheckvalue; 69 | } 70 | } 71 | 72 | if (foundValue) 73 | _results.Add(result); 74 | } 75 | 76 | return _results; 77 | } 78 | 79 | public static new CaseInsensitiveList Aliases 80 | { 81 | get { return new CaseInsensitiveList() { "Where-Object", "where", "?" }; } 82 | } 83 | 84 | public static new ArgumentList SupportedArguments 85 | { 86 | get 87 | { 88 | return new ArgumentList() 89 | { 90 | new StringArgument("Property"), 91 | new BoolArgument("EQ"), 92 | new BoolArgument("NE"), 93 | new BoolArgument("Like"), 94 | new StringArgument("Value") 95 | }; 96 | } 97 | } 98 | 99 | public static new string Synopsis 100 | { 101 | get { return "Selects objects from a collection based on their property values."; } 102 | } 103 | 104 | public static new ExampleEntries Examples 105 | { 106 | get 107 | { 108 | return new ExampleEntries() 109 | { 110 | new ExampleEntry("List all processes containing PowerShell in the process name", "Get-Process | ? Name -Like *PowerShell*"), 111 | new ExampleEntry("List all active local users", "Get-LocalUser | ? Disabled -EQ False") 112 | }; 113 | } 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/DnsClient/GetDnsClientCacheCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Management 13 | { 14 | public class GetDnsClientCacheCommand : PSCommand 15 | { 16 | public GetDnsClientCacheCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Collect parameters for remote execution 23 | base.Execute(); 24 | 25 | CommandResult dnsClientCache = WmiHelper.ExecuteWmiQuery("root/StandardCimv2", "Select Entry, Name, Type, Status, Section, TimeToLive, DataLength, Data From MSFT_DNSClientCache", computername, username, password); 26 | foreach (ResultRecord entry in dnsClientCache) 27 | { 28 | DnsHelper.DnsRecordTypes recordType = (DnsHelper.DnsRecordTypes)Convert.ToInt32(entry["Type"]); 29 | int status = Convert.ToInt32(entry["Status"]); 30 | string strStatus; 31 | switch(status) 32 | { 33 | case 0: 34 | strStatus = "Success"; 35 | break; 36 | case 9003: 37 | strStatus = "NotExist"; 38 | break; 39 | case 9701: 40 | strStatus = "NoRecords"; 41 | break; 42 | default: 43 | strStatus = "Unknown"; 44 | break; 45 | } 46 | 47 | _results.Add( 48 | new ResultRecord() 49 | { 50 | { "Entry", entry["Entry"] }, 51 | { "RecordName", entry["Name"] }, 52 | { "RecordType", recordType.ToString().Replace("DNS_TYPE_","") }, 53 | { "Status", strStatus }, 54 | { "Section", entry["Section"] }, 55 | { "TimeToLive", entry["TimeToLive"] }, 56 | { "DataLength", entry["DataLength"] }, 57 | { "Data", entry["Data"] } 58 | } 59 | ); 60 | } 61 | 62 | return _results; 63 | } 64 | 65 | public static new CaseInsensitiveList Aliases 66 | { 67 | get { return new CaseInsensitiveList() { "Get-DnsClientCache" }; } 68 | } 69 | 70 | public static new ArgumentList SupportedArguments 71 | { 72 | get 73 | { 74 | return new ArgumentList() 75 | { 76 | }; 77 | } 78 | } 79 | 80 | public static new string Synopsis 81 | { 82 | get { return "Retrieves the contents of the DNS client cache."; } 83 | } 84 | 85 | public static new ExampleEntries Examples 86 | { 87 | get 88 | { 89 | return new ExampleEntries() 90 | { 91 | new ExampleEntry("List cached DNS entries on the local computer", "Get-DnsClientCache"), 92 | new ExampleEntry 93 | ( 94 | "List cached DNS entries from a remote computer using WMI", 95 | new List() 96 | { 97 | "Get-DnsClientCache -ComputerName MyServer -Username Administrator -Password Pa$$w0rd", 98 | "Get-DnsClientCache -ComputerName MyServer" 99 | } 100 | ) 101 | }; 102 | } 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/DnsClient/ResolveDnsNameCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.DnsClient 12 | { 13 | public class ResolveDnsNameCommand : PSCommand 14 | { 15 | public ResolveDnsNameCommand(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | // Obtain cmdlet parameters 22 | string query = _arguments.Get("Name").Value; 23 | string type = _arguments.Get("Type").Value; 24 | 25 | _results = DnsHelper.GetRecords(query, type); 26 | 27 | // Determine columns in results 28 | List columns = new List(); 29 | foreach (ResultRecord r in _results) 30 | foreach (string c in r.Keys) 31 | if (!columns.Contains(c)) 32 | columns.Add(c); 33 | 34 | // Add missing columns 35 | foreach (ResultRecord r in _results) 36 | { 37 | foreach (string c in columns) 38 | { 39 | if (!r.ContainsKey(c)) 40 | r.Add(c, null); 41 | } 42 | } 43 | 44 | return _results; 45 | } 46 | 47 | public static new CaseInsensitiveList Aliases 48 | { 49 | get 50 | { 51 | return new CaseInsensitiveList() 52 | { 53 | "Resolve-DnsName", 54 | "nslookup", "host" // Not official 55 | }; 56 | } 57 | } 58 | 59 | public static new ArgumentList SupportedArguments 60 | { 61 | get 62 | { 63 | return new ArgumentList() 64 | { 65 | new StringArgument("Name"), 66 | new StringArgument("Type", "A", true) 67 | // TODO: 68 | //new StringArgument("Server", true), 69 | }; 70 | } 71 | } 72 | 73 | public static new string Synopsis 74 | { 75 | get 76 | { 77 | return string.Format("Resolve DNS name."); 78 | } 79 | } 80 | 81 | public static new ExampleEntries Examples 82 | { 83 | get 84 | { 85 | return new ExampleEntries() 86 | { 87 | new ExampleEntry 88 | ( 89 | "Resolve domain name", 90 | new List() 91 | { 92 | "Resolve-DnsName microsoft.com", 93 | "host linux.org", 94 | } 95 | ), 96 | new ExampleEntry("Lookup specific record", "Resolve-DnsName -Type MX pm.me"), 97 | new ExampleEntry("Reverse DNS lookup", "Resolve-DnsName 1.1.1.1") 98 | }; 99 | } 100 | } 101 | } 102 | } -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/LocalAccounts/GetLocalGroupCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.LocalAccounts 12 | { 13 | public class GetLocalGroupCommand : PSCommand 14 | { 15 | public GetLocalGroupCommand(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | string name = _arguments.Get("Name").Value; 22 | string sid = _arguments.Get("SID").Value; 23 | 24 | string query = "Select Name, Description{0} From Win32_Group Where LocalAccount='True'{1}"; 25 | 26 | if (!string.IsNullOrEmpty(name)) 27 | query = string.Format(query, ", SID", string.Format(" And Name='{0}'", name)); 28 | else if (!string.IsNullOrEmpty(sid)) 29 | query = string.Format(query, ", SID", string.Format(" And SID='{0}'", sid)); 30 | else 31 | query = string.Format(query, string.Empty, string.Empty); 32 | 33 | _results = WmiHelper.ExecuteWmiQuery(query, computername, username, password); 34 | 35 | return _results; 36 | } 37 | 38 | public static new CaseInsensitiveList Aliases 39 | { 40 | get { return new CaseInsensitiveList() { "Get-LocalGroup", "glg" }; } 41 | } 42 | 43 | public static new ArgumentList SupportedArguments 44 | { 45 | get 46 | { 47 | return new ArgumentList() 48 | { 49 | new StringArgument("Name"), 50 | new StringArgument("SID", true) 51 | }; 52 | } 53 | } 54 | 55 | public static new string Synopsis 56 | { 57 | get { return "Gets the local security groups."; } 58 | } 59 | 60 | public static new ExampleEntries Examples 61 | { 62 | get 63 | { 64 | return new ExampleEntries() 65 | { 66 | new ExampleEntry("List all local groups", "Get-LocalGroup"), 67 | new ExampleEntry("List details of a specific group", "Get-LocalGroup Administrators"), 68 | new ExampleEntry 69 | ( 70 | "List members of Administrators group on a remote computer using WMI", 71 | new List() 72 | { 73 | "Get-LocalGroup -ComputerName Myserver -Username MyUser -Password MyPassword -Name Administrators", 74 | "Get-LocalGroup -ComputerName Myserver -Name Administrators" 75 | } 76 | ) 77 | }; 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/LocalAccounts/GetLocalUserCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.LocalAccounts 12 | { 13 | public class GetLocalUserCommand : PSCommand 14 | { 15 | public GetLocalUserCommand(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | string name = _arguments.Get("Name").Value; 22 | string sid = _arguments.Get("SID").Value; 23 | 24 | string query = "Select Name, Description, Disabled{0} From Win32_UserAccount{1}"; 25 | 26 | if (!string.IsNullOrEmpty(name)) 27 | query = string.Format(query, ", SID", string.Format(" Where Name='{0}'", name)); 28 | else if (!string.IsNullOrEmpty(sid)) 29 | query = string.Format(query, ", SID", string.Format(" Where SID='{0}'", sid)); 30 | else 31 | query = string.Format(query, string.Empty, string.Empty); 32 | 33 | _results = WmiHelper.ExecuteWmiQuery(query, computername, username, password); 34 | 35 | return _results; 36 | } 37 | 38 | public static new CaseInsensitiveList Aliases 39 | { 40 | get { return new CaseInsensitiveList() { "Get-LocalUser", "glu" }; } 41 | } 42 | 43 | public static new ArgumentList SupportedArguments 44 | { 45 | get 46 | { 47 | return new ArgumentList() 48 | { 49 | new StringArgument("Name"), 50 | new StringArgument("SID", true) 51 | }; 52 | } 53 | } 54 | 55 | public static new string Synopsis 56 | { 57 | get { return "Gets local user accounts."; } 58 | } 59 | 60 | public static new ExampleEntries Examples 61 | { 62 | get 63 | { 64 | return new ExampleEntries() 65 | { 66 | new ExampleEntry("List all local users", "Get-LocalUser"), 67 | new ExampleEntry 68 | ( 69 | "List details of a specific user", 70 | new List() 71 | { 72 | "Get-LocalUser -Name Administrator", 73 | "Get-LocalUser Administrator" 74 | } 75 | ), 76 | new ExampleEntry 77 | ( 78 | "List details of a specific user on a remote machine using WMI", 79 | new List() 80 | { 81 | "Get-LocalUser -ComputerName MyServer -Username MyUser -Password MyPassword -Name Administrator", 82 | "Get-LocalUser -ComputerName MyServer Administrator" 83 | } 84 | ) 85 | }; 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/CopyItemCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Management 13 | { 14 | public class CopyItemCommand : PSCommand 15 | { 16 | public CopyItemCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Obtain source and destination 23 | string path = _arguments.Get("Path").Value; 24 | string destination = _arguments.Get("Destination").Value; 25 | bool force = _arguments.Get("Force").Value; 26 | 27 | // Determine if provided path is a file or a directory 28 | FileAttributes attr = File.GetAttributes(path); 29 | 30 | // Directory 31 | if((attr & FileAttributes.Directory) == FileAttributes.Directory) 32 | { 33 | DirectoryCopy(path, destination, force); 34 | } 35 | // File 36 | else 37 | { 38 | File.Copy(path, destination, force); 39 | } 40 | 41 | return _results; 42 | } 43 | 44 | // Slightly modified version of: 45 | // https://docs.microsoft.com/dotnet/standard/io/how-to-copy-directories 46 | private static void DirectoryCopy(string sourceDirName, string destDirName, bool force) 47 | { 48 | // Get the subdirectories for the specified directory. 49 | DirectoryInfo dir = new DirectoryInfo(sourceDirName); 50 | 51 | if (!dir.Exists) 52 | { 53 | throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName); 54 | } 55 | 56 | DirectoryInfo[] dirs = dir.GetDirectories(); 57 | // If the destination directory doesn't exist, create it. 58 | if (!Directory.Exists(destDirName)) 59 | { 60 | Directory.CreateDirectory(destDirName); 61 | } 62 | 63 | // Get the files in the directory and copy them to the new location. 64 | FileInfo[] files = dir.GetFiles(); 65 | foreach (FileInfo file in files) 66 | { 67 | string destPath = Path.Combine(destDirName, file.Name); 68 | file.CopyTo(destPath, force); 69 | } 70 | 71 | // Copy subdirectories and their contents to new location. 72 | foreach (DirectoryInfo subdir in dirs) 73 | { 74 | string temppath = Path.Combine(destDirName, subdir.Name); 75 | DirectoryCopy(subdir.FullName, temppath, force); 76 | } 77 | } 78 | 79 | public static new CaseInsensitiveList Aliases 80 | { 81 | get { return new CaseInsensitiveList() { "Copy-Item", "copy", "cp", "cpi" }; } 82 | } 83 | 84 | public static new ArgumentList SupportedArguments 85 | { 86 | get 87 | { 88 | return new ArgumentList() 89 | { 90 | new StringArgument("Path"), 91 | new StringArgument("Destination"), 92 | new BoolArgument("Force") 93 | }; 94 | } 95 | } 96 | 97 | public static new string Synopsis 98 | { 99 | get { return "Copies an item from one location to another."; } 100 | } 101 | 102 | public static new ExampleEntries Examples 103 | { 104 | get 105 | { 106 | return new ExampleEntries() 107 | { 108 | new ExampleEntry 109 | ( 110 | "Copy file from one location to another", 111 | new List() 112 | { 113 | "Copy-Item C:\\Tmp\\nc.exe C:\\Windows\\System32\\nc.exe", 114 | "copy C:\\Tmp\\nc.exe C:\\Windows\\System32\\nc.exe", 115 | } 116 | ), 117 | new ExampleEntry("Copy folder", "copy C:\\Tmp\\MyFolder C:\\Tmp\\MyFolderBackup") 118 | }; 119 | } 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetClipboardCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Windows.Forms; 6 | 7 | /* 8 | Author: @bitsadmin 9 | Website: https://github.com/bitsadmin 10 | License: BSD 3-Clause 11 | */ 12 | 13 | namespace NoPowerShell.Commands.Management 14 | { 15 | public class GetClipboardCommand : PSCommand 16 | { 17 | public GetClipboardCommand(string[] userArguments) : base(userArguments, SupportedArguments) 18 | { 19 | } 20 | 21 | public override CommandResult Execute(CommandResult pipeIn) 22 | { 23 | // Obtain cmdlet parameters 24 | //bool showHistory = _arguments.Get("History").Value; 25 | 26 | _results.Add( 27 | new ResultRecord() 28 | { 29 | { "Data", Clipboard.GetText() } 30 | } 31 | ); 32 | 33 | return _results; 34 | } 35 | 36 | public static new CaseInsensitiveList Aliases 37 | { 38 | get { return new CaseInsensitiveList() { "Get-Clipboard", "gcb" }; } 39 | } 40 | 41 | public static new ArgumentList SupportedArguments 42 | { 43 | get 44 | { 45 | return new ArgumentList() 46 | { 47 | //new BoolArgument("History") 48 | }; 49 | } 50 | } 51 | 52 | public static new string Synopsis 53 | { 54 | get { return "Gets the current Windows clipboard entry."; } 55 | } 56 | 57 | public static new ExampleEntries Examples 58 | { 59 | get 60 | { 61 | return new ExampleEntries() 62 | { 63 | new ExampleEntry 64 | ( 65 | "Show text contents of clipboard", 66 | new List() 67 | { 68 | "Get-Clipboard", 69 | "gcb" 70 | } 71 | ) 72 | }; 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetContentCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Management 13 | { 14 | public class GetContentCommand : PSCommand 15 | { 16 | public GetContentCommand(string[] arguments) : base(arguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | string path = _arguments.Get("Path").Value; 23 | string txt = File.ReadAllText(path); 24 | 25 | // Create a single ResultRecord with an empty name to simply display raw output 26 | _results.Add( 27 | new ResultRecord() { 28 | { string.Empty, txt } 29 | } 30 | ); 31 | 32 | return _results; 33 | } 34 | 35 | public static new CaseInsensitiveList Aliases 36 | { 37 | get { return new CaseInsensitiveList() { "Get-Content", "gc", "cat", "type" }; } 38 | } 39 | 40 | public static new ArgumentList SupportedArguments 41 | { 42 | get 43 | { 44 | return new ArgumentList() 45 | { 46 | new StringArgument("Path") 47 | }; 48 | } 49 | } 50 | 51 | public static new string Synopsis 52 | { 53 | get { return "Gets the contents of a file."; } 54 | } 55 | 56 | public static new ExampleEntries Examples 57 | { 58 | get 59 | { 60 | return new ExampleEntries() 61 | { 62 | new ExampleEntry 63 | ( 64 | "View contents of a file", 65 | new List() 66 | { 67 | "Get-Content C:\\Windows\\WindowsUpdate.log", 68 | "cat C:\\Windows\\WindowsUpdate.log" 69 | } 70 | ) 71 | }; 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetHotFixCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Management 13 | { 14 | public class GetHotFixCommand : PSCommand 15 | { 16 | public GetHotFixCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Collect parameters for remote execution 23 | base.Execute(); 24 | 25 | CommandResult wmiHotfixes = WmiHelper.ExecuteWmiQuery("Select CSName,Description,HotFixID,InstalledBy,InstalledOn From Win32_QuickFixEngineering", computername, username, password); 26 | foreach (ResultRecord hotfix in wmiHotfixes) 27 | { 28 | _results.Add( 29 | new ResultRecord() 30 | { 31 | { "Source", hotfix["CSName"] }, 32 | { "Description", hotfix["Description"] }, 33 | { "HotFixID", hotfix["HotFixID"] }, 34 | { "InstalledBy", hotfix["InstalledBy"] }, 35 | { "InstalledOn", hotfix["InstalledOn"] } 36 | } 37 | ); 38 | } 39 | 40 | return _results; 41 | } 42 | 43 | public static new CaseInsensitiveList Aliases 44 | { 45 | get { return new CaseInsensitiveList() { "Get-HotFix" }; } 46 | } 47 | 48 | public static new ArgumentList SupportedArguments 49 | { 50 | get 51 | { 52 | return new ArgumentList() 53 | { 54 | }; 55 | } 56 | } 57 | 58 | public static new string Synopsis 59 | { 60 | get { return "Gets the hotfixes that have been applied to the local and remote computers."; } 61 | } 62 | 63 | public static new ExampleEntries Examples 64 | { 65 | get 66 | { 67 | return new ExampleEntries() 68 | { 69 | new ExampleEntry("Get all hotfixes on the local computer", "Get-HotFix"), 70 | new ExampleEntry 71 | ( 72 | "Get all hotfixes from a remote computer using WMI", 73 | new List() 74 | { 75 | "Get-HotFix -ComputerName MyServer -Username Administrator -Password Pa$$w0rd", 76 | "Get-HotFix -ComputerName MyServer" 77 | } 78 | ) 79 | }; 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetItemPropertyCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using Microsoft.Win32; 5 | using System.Collections.Generic; 6 | 7 | /* 8 | Author: @bitsadmin 9 | Website: https://github.com/bitsadmin 10 | License: BSD 3-Clause 11 | */ 12 | 13 | namespace NoPowerShell.Commands.Management 14 | { 15 | public class GetItemPropertyCommand : PSCommand 16 | { 17 | public GetItemPropertyCommand(string[] arguments) : base(arguments, SupportedArguments) 18 | { 19 | } 20 | 21 | public override CommandResult Execute(CommandResult pipeIn) 22 | { 23 | // Obtain parameters 24 | bool includeHidden = _arguments.Get("Force").Value; 25 | string path = _arguments.Get("Path").Value; 26 | string[] searchPatterns = _arguments.Get("Include").Value.Split(new char[] { ',' }); 27 | string name = _arguments.Get("Name").Value; 28 | CaseInsensitiveList attributeNames = null; 29 | if (!string.IsNullOrEmpty(name)) 30 | attributeNames = new CaseInsensitiveList(name.Split(',')); 31 | 32 | // Registry: 33 | // HKLM:\ 34 | // HKCU:\ 35 | // HKCR:\ 36 | // HKU:\ 37 | if (RegistryHelper.IsRegistryPath(path)) 38 | _results = BrowseRegistry(path, attributeNames); 39 | 40 | // Filesystem: 41 | // \ 42 | // ..\ 43 | // D:\ 44 | else 45 | _results = GetChildItemCommand.BrowseFilesystem(path, false, 1, includeHidden, searchPatterns); 46 | 47 | return _results; 48 | } 49 | 50 | private CommandResult BrowseRegistry(string path, CaseInsensitiveList attributeNames) 51 | { 52 | RegistryKey root = RegistryHelper.GetRoot(ref path); 53 | 54 | RegistryKey key = root.OpenSubKey(path); 55 | foreach (string valueName in key.GetValueNames()) 56 | { 57 | string valueKind = key.GetValueKind(valueName).ToString(); 58 | string value = Convert.ToString(key.GetValue(valueName)); 59 | 60 | // Skip if -Names parameter is provided and current attribute is not in the list 61 | if (attributeNames != null && !attributeNames.Contains(valueName)) 62 | continue; 63 | 64 | _results.Add( 65 | new ResultRecord() 66 | { 67 | { "Name", valueName }, 68 | { "Kind", valueKind }, 69 | { "Value", value } 70 | } 71 | ); 72 | } 73 | 74 | return _results; 75 | } 76 | 77 | public static new CaseInsensitiveList Aliases 78 | { 79 | get { return new CaseInsensitiveList() { "Get-ItemProperty", "gp" }; } 80 | } 81 | 82 | public static new ArgumentList SupportedArguments 83 | { 84 | get 85 | { 86 | return new ArgumentList() 87 | { 88 | new StringArgument("Path", "."), 89 | new BoolArgument("Force") , 90 | new StringArgument("Include", "*", true), 91 | new StringArgument("Name", true) 92 | }; 93 | } 94 | } 95 | 96 | public static new string Synopsis 97 | { 98 | get { return "Gets the properties of a specified item."; } 99 | } 100 | 101 | public static new ExampleEntries Examples 102 | { 103 | get 104 | { 105 | return new ExampleEntries() 106 | { 107 | new ExampleEntry("List autoruns in the registry", @"Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Run | ft") 108 | }; 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetItemPropertyValueCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using Microsoft.Win32; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | /* 9 | Author: @bitsadmin 10 | Website: https://github.com/bitsadmin 11 | License: BSD 3-Clause 12 | */ 13 | 14 | namespace NoPowerShell.Commands.Management 15 | { 16 | public class GetItemPropertyValueCommand : PSCommand 17 | { 18 | public GetItemPropertyValueCommand(string[] arguments) : base(arguments, SupportedArguments) 19 | { 20 | } 21 | 22 | public override CommandResult Execute(CommandResult pipeIn) 23 | { 24 | // Obtain parameters 25 | string path = _arguments.Get("Path").Value; 26 | string name = _arguments.Get("Name").Value; 27 | CaseInsensitiveList attributeNames = null; 28 | if (!string.IsNullOrEmpty(name)) 29 | attributeNames = new CaseInsensitiveList(name.Split(',')); 30 | 31 | // Registry: 32 | // HKLM:\ 33 | // HKCU:\ 34 | // HKCR:\ 35 | // HKU:\ 36 | if (RegistryHelper.IsRegistryPath(path)) 37 | _results = BrowseRegistry(path, attributeNames); 38 | 39 | // Filesystem: 40 | // \ 41 | // ..\ 42 | // D:\ 43 | else // TODO 44 | throw new NoPowerShellException("At this moment Get-ItemPropertyValue only supports registry."); 45 | 46 | return _results; 47 | } 48 | 49 | private CommandResult BrowseRegistry(string path, CaseInsensitiveList attributeNames) 50 | { 51 | RegistryKey root = RegistryHelper.GetRoot(ref path); 52 | 53 | RegistryKey key = root.OpenSubKey(path); 54 | foreach (string attr in attributeNames) 55 | { 56 | object value = key.GetValue(attr); 57 | RegistryValueKind kind = key.GetValueKind(attr); 58 | 59 | string strValue; 60 | switch (kind) 61 | { 62 | case RegistryValueKind.DWord: 63 | strValue = Convert.ToInt32(value).ToString(); 64 | break; 65 | case RegistryValueKind.QWord: 66 | strValue = Convert.ToInt64(value).ToString(); 67 | break; 68 | case RegistryValueKind.MultiString: 69 | strValue = string.Join(";", (string[])value); 70 | break; 71 | case RegistryValueKind.String: 72 | case RegistryValueKind.ExpandString: 73 | strValue = value.ToString(); 74 | break; 75 | case RegistryValueKind.Binary: 76 | byte[] bValue = (byte[])value; 77 | _results.Add( 78 | new ResultRecord() 79 | { 80 | { "Value", System.Text.Encoding.ASCII.GetString(bValue) }, 81 | { "Hex", BitConverter.ToString(bValue).Replace('-', ' ') }, 82 | { "Base64", Convert.ToBase64String(bValue) } 83 | } 84 | ); 85 | continue; 86 | default: 87 | strValue = value.ToString(); 88 | break; 89 | } 90 | 91 | _results.Add( 92 | new ResultRecord() 93 | { 94 | { "Value", strValue } 95 | } 96 | ); 97 | } 98 | 99 | return _results; 100 | } 101 | 102 | public static new CaseInsensitiveList Aliases 103 | { 104 | get { return new CaseInsensitiveList() { "Get-ItemPropertyValue", "gpv" }; } 105 | } 106 | 107 | public static new ArgumentList SupportedArguments 108 | { 109 | get 110 | { 111 | return new ArgumentList() 112 | { 113 | new StringArgument("Path", false), 114 | new StringArgument("Name", false) 115 | }; 116 | } 117 | } 118 | 119 | public static new string Synopsis 120 | { 121 | get { return "Gets the value for one or more properties of a specified item."; } 122 | } 123 | 124 | public static new ExampleEntries Examples 125 | { 126 | get 127 | { 128 | return new ExampleEntries() 129 | { 130 | new ExampleEntry 131 | ( 132 | "Show current user's PATH variable", 133 | new List() 134 | { 135 | @"Get-ItemPropertyValue -Path HKCU:\Environment -Name Path", 136 | @"gpv HKCU:\Environment Path" 137 | } 138 | ) 139 | }; 140 | } 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetPSDriveCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | 7 | /* 8 | Author: @bitsadmin 9 | Website: https://github.com/bitsadmin 10 | License: BSD 3-Clause 11 | */ 12 | 13 | namespace NoPowerShell.Commands.Management 14 | { 15 | public class GetPSDriveCommand : PSCommand 16 | { 17 | public GetPSDriveCommand(string[] userArguments) : base(userArguments, SupportedArguments) 18 | { 19 | } 20 | 21 | public override CommandResult Execute(CommandResult pipeIn) 22 | { 23 | // Enumerate harddrives 24 | DriveInfo[] drives = DriveInfo.GetDrives(); 25 | foreach (DriveInfo drive in drives) 26 | { 27 | _results.Add( 28 | new ResultRecord() 29 | { 30 | { "Name", drive.Name[0].ToString() }, 31 | { "Used (GB)", drive.IsReady ? ((drive.TotalSize - drive.TotalFreeSpace) / Math.Pow(1024,3)).ToString("0.00") : "" }, 32 | { "Free (GB)", drive.IsReady ? (drive.TotalFreeSpace / Math.Pow(1024,3)).ToString("0.00") : "" }, 33 | { "Provider", "FileSystem" }, 34 | { "Root", drive.Name } 35 | } 36 | ); 37 | } 38 | 39 | // Complement with environment and registry 40 | _results.AddRange( 41 | new List() 42 | { 43 | new ResultRecord() 44 | { 45 | { "Name", "Env" }, 46 | { "Used (GB)", "" }, 47 | { "Free (GB)", "" }, 48 | { "Provider", "Environment" }, 49 | { "Root", "" } 50 | }, 51 | new ResultRecord() 52 | { 53 | { "Name", "HKCU" }, 54 | { "Used (GB)", "" }, 55 | { "Free (GB)", "" }, 56 | { "Provider", "Registry" }, 57 | { "Root", "HKEY_CURRENT_USER" } 58 | }, 59 | new ResultRecord() 60 | { 61 | { "Name", "HKLM" }, 62 | { "Used (GB)", "" }, 63 | { "Free (GB)", "" }, 64 | { "Provider", "Registry" }, 65 | { "Root", "HKEY_LOCAL_MACHINE" } 66 | } 67 | } 68 | ); 69 | 70 | return _results; 71 | } 72 | 73 | public static new CaseInsensitiveList Aliases 74 | { 75 | get { return new CaseInsensitiveList() { "Get-PSDrive", "gdr" }; } 76 | } 77 | 78 | public static new ArgumentList SupportedArguments 79 | { 80 | get 81 | { 82 | return new ArgumentList() 83 | { 84 | }; 85 | } 86 | } 87 | 88 | public static new string Synopsis 89 | { 90 | get { return "Gets drives in the current session."; } 91 | } 92 | 93 | public static new ExampleEntries Examples 94 | { 95 | get 96 | { 97 | return new ExampleEntries() 98 | { 99 | new ExampleEntry 100 | ( 101 | "List drives", 102 | new List() 103 | { 104 | "Get-PSDrive", 105 | "gdr" 106 | } 107 | ) 108 | }; 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetProcessCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Management 13 | { 14 | public class GetProcessCommand : PSCommand 15 | { 16 | public GetProcessCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Collect parameters for remote execution 23 | base.Execute(); 24 | 25 | string allNameArguments = _arguments.Get("Name").Value; 26 | 27 | string where = string.Empty; 28 | if (!string.IsNullOrEmpty(allNameArguments)) 29 | { 30 | string[] processNames = allNameArguments.Split(','); 31 | StringBuilder whereStr = new StringBuilder(" Where ("); 32 | 33 | bool first = true; 34 | foreach (string name in processNames) 35 | { 36 | string newname = name; 37 | if (!name.ToUpperInvariant().EndsWith(".EXE")) 38 | newname = name + ".exe"; 39 | 40 | if (first) 41 | { 42 | whereStr.AppendFormat("(name = '{0}')", newname); 43 | first = false; 44 | } 45 | else 46 | { 47 | whereStr.AppendFormat(" or (name = '{0}')", newname); 48 | } 49 | } 50 | 51 | whereStr.Append(")"); 52 | where = whereStr.ToString(); 53 | } 54 | 55 | _results = WmiHelper.ExecuteWmiQuery("Select ProcessId, Name, CommandLine From Win32_Process" + where, computername, username, password); 56 | 57 | if(_results.Count == 0) 58 | { 59 | throw new NoPowerShellException("Cannot find a process with the name \"{0}\". Verify the process name and call the cmdlet again.", allNameArguments); 60 | } 61 | 62 | return _results; 63 | } 64 | 65 | public static new CaseInsensitiveList Aliases 66 | { 67 | get { return new CaseInsensitiveList() { "Get-Process", "ps" }; } 68 | } 69 | 70 | public static new ArgumentList SupportedArguments 71 | { 72 | get 73 | { 74 | return new ArgumentList() 75 | { 76 | new StringArgument("Name", string.Empty) 77 | }; 78 | } 79 | } 80 | 81 | public static new string Synopsis 82 | { 83 | get { return "Gets the processes that are running on the local computer or a remote computer."; } 84 | } 85 | 86 | public static new ExampleEntries Examples 87 | { 88 | get 89 | { 90 | return new ExampleEntries() 91 | { 92 | new ExampleEntry 93 | ( 94 | "List processes", 95 | new List() 96 | { 97 | "Get-Process", 98 | "ps" 99 | } 100 | ), 101 | new ExampleEntry 102 | ( 103 | "List processes on remote host using WMI", 104 | new List() 105 | { 106 | "Get-Process -ComputerName dc01.corp.local -Username Administrator -Password P4ssw0rd!", 107 | "ps -ComputerName dc01.corp.local" 108 | } 109 | ) 110 | }; 111 | } 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/GetWmiObjectCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.Management 12 | { 13 | public class GetWmiObjectCommand : PSCommand 14 | { 15 | public GetWmiObjectCommand(string[] arguments) : base(arguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | // Collect parameters for remote execution 22 | base.Execute(); 23 | 24 | // Obtain parameters 25 | string wmiNamespace = _arguments.Get("Namespace").Value; 26 | string wmiQuery = _arguments.Get("Query").Value; 27 | string wmiClass = _arguments.Get("Class").Value; 28 | string wmiFilter = _arguments.Get("Filter").Value; 29 | 30 | // If no query is specified, assume a class is specified 31 | if (wmiQuery != null && !wmiQuery.ToUpperInvariant().Contains("SELECT")) 32 | wmiClass = wmiQuery; 33 | 34 | if (wmiClass != null) 35 | wmiQuery = string.Format("Select * From {0}", wmiClass); 36 | if (wmiFilter != null) 37 | wmiQuery += string.Format(" Where {0}", wmiFilter); 38 | 39 | // Execute user provided WMI query 40 | _results = WmiHelper.ExecuteWmiQuery(wmiNamespace, wmiQuery, computername, username, password); 41 | 42 | return _results; 43 | } 44 | 45 | public static new CaseInsensitiveList Aliases 46 | { 47 | get { return new CaseInsensitiveList() { "Get-WmiObject", "gwmi" }; } 48 | } 49 | 50 | public static new ArgumentList SupportedArguments 51 | { 52 | get 53 | { 54 | return new ArgumentList() 55 | { 56 | new StringArgument("Namespace", @"ROOT\CIMV2", true), 57 | new StringArgument("Query"), 58 | new StringArgument("Class", true), 59 | new StringArgument("Filter", true) 60 | }; 61 | } 62 | } 63 | 64 | public static new string Synopsis 65 | { 66 | get { return "Gets instances of WMI classes or information about the available classes."; } 67 | } 68 | 69 | public static new ExampleEntries Examples 70 | { 71 | get 72 | { 73 | return new ExampleEntries() 74 | { 75 | new ExampleEntry 76 | ( 77 | "List local shares", 78 | new List() 79 | { 80 | "Get-WmiObject -Namespace ROOT\\CIMV2 -Query \"Select * From Win32_Share Where Name LIKE '%$'\"", 81 | "gwmi -Class Win32_Share -Filter \"Name LIKE '%$'\"" 82 | } 83 | ), 84 | new ExampleEntry 85 | ( 86 | "Obtain data of Win32_Process class from a remote system and apply a filter on the output", 87 | new List() 88 | { 89 | "Get-WmiObject \"Select ProcessId,Name,CommandLine From Win32_Process\" -ComputerName dc01.corp.local -Username MyUser -Password MyPassword | ? Name -Like *PowerShell* | select ProcessId,CommandLine", 90 | "gwmi \"Select ProcessId,Name,CommandLine From Win32_Process\" -ComputerName dc01.corp.local | ? Name -Like *PowerShell* | select ProcessId,CommandLine" 91 | } 92 | ), 93 | new ExampleEntry("View details about a certain service", "Get-WmiObject -Class Win32_Service -Filter \"Name = 'WinRM'\"") 94 | }; 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/InvokeWmiMethodCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.Management 12 | { 13 | public class InvokeWmiMethodCommand : PSCommand 14 | { 15 | public InvokeWmiMethodCommand(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | // Collect parameters for remote execution 22 | base.Execute(); 23 | 24 | // Obtain parameters 25 | string wmiNamespace = _arguments.Get("Namespace").Value; 26 | string wmiClass = _arguments.Get("Class").Value; 27 | string methodName = _arguments.Get("Name").Value; 28 | string methodArguments = _arguments.Get("ArgumentList").Value; 29 | 30 | // Invoke WMI method 31 | _results = WmiHelper.InvokeWmiMethod(wmiNamespace, wmiClass, methodName, methodArguments, computername, username, password); 32 | 33 | return _results; 34 | } 35 | 36 | public static new CaseInsensitiveList Aliases 37 | { 38 | get { return new CaseInsensitiveList() { "Invoke-WmiMethod", "iwmi" }; } 39 | } 40 | 41 | public static new ArgumentList SupportedArguments 42 | { 43 | get 44 | { 45 | return new ArgumentList() 46 | { 47 | new StringArgument("Namespace", @"root\cimv2", true), 48 | new StringArgument("Class"), 49 | new StringArgument("Name"), 50 | new StringArgument("ArgumentList") 51 | }; 52 | } 53 | } 54 | 55 | public static new string Synopsis 56 | { 57 | get { return "Calls WMI methods."; } 58 | } 59 | 60 | public static new ExampleEntries Examples 61 | { 62 | get 63 | { 64 | return new ExampleEntries() 65 | { 66 | new ExampleEntry("Launch process", "Invoke-WmiMethod -Class Win32_Process -Name Create \"cmd /c calc.exe\""), 67 | new ExampleEntry 68 | ( 69 | "Launch process on remote system", 70 | new List() 71 | { 72 | "Invoke-WmiMethod -ComputerName MyServer -Username MyUserName -Password MyPassword -Class Win32_Process -Name Create \"powershell -NoP -W H -E ZQBjAGgAbwAgACcASABlAGwAbABvACAATgBvAFAAbwB3AGUAcgBTAGgAZQBsAGwAIQAnAA==\"", 73 | "iwmi -ComputerName MyServer -Class Win32_Process -Name Create \"powershell -NoP -W H -E ZQBjAGgAbwAgACcASABlAGwAbABvACAATgBvAFAAbwB3AGUAcgBTAGgAZQBsAGwAIQAnAA==\"" 74 | } 75 | ), 76 | }; 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/RemoveItemCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Management 13 | { 14 | public class RemoveItemCommand : PSCommand 15 | { 16 | public RemoveItemCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Obtain source and destination 23 | string path = _arguments.Get("Path").Value; 24 | bool force = _arguments.Get("Force").Value; 25 | bool recurse = _arguments.Get("Recurse").Value; 26 | 27 | // Determine if provided path is a file or a directory 28 | if (!File.Exists(path)) 29 | throw new NoPowerShellException("Cannot find path '{0}' because it does not exist.", path); 30 | 31 | FileAttributes attr = File.GetAttributes(path); 32 | 33 | // Directory 34 | if ((attr & FileAttributes.Directory) == FileAttributes.Directory) 35 | { 36 | DirectoryDelete(path, recurse, force); 37 | Directory.Delete(path); 38 | } 39 | // File 40 | else 41 | { 42 | // Remove readonly attribute 43 | if(force) 44 | File.SetAttributes(path, attr & ~FileAttributes.ReadOnly); 45 | 46 | File.Delete(path); 47 | } 48 | 49 | return _results; 50 | } 51 | 52 | // Inspired by: 53 | // https://docs.microsoft.com/dotnet/standard/io/how-to-copy-directories 54 | private static void DirectoryDelete(string dirName, bool recurse, bool force) 55 | { 56 | // Get the subdirectories for the specified directory. 57 | DirectoryInfo dir = new DirectoryInfo(dirName); 58 | DirectoryInfo[] dirs = dir.GetDirectories(); 59 | 60 | if (dirs.Length > 0 && !recurse) 61 | throw new System.Exception(string.Format("The item at {0} has children and the Recurse parameter was not specified. Nothing has been removed.", dirName)); 62 | 63 | // Get the files in the directory and copy them to the new location. 64 | FileInfo[] files = dir.GetFiles(); 65 | foreach (FileInfo file in files) 66 | { 67 | // Remove readonly attribute 68 | if (force) 69 | File.SetAttributes(file.FullName, file.Attributes & ~FileAttributes.ReadOnly); 70 | 71 | file.Delete(); 72 | } 73 | 74 | // Remove subdirectories and their contents if Recurse flag is set 75 | if (recurse) 76 | { 77 | foreach (DirectoryInfo subdir in dirs) 78 | { 79 | DirectoryDelete(subdir.FullName, recurse, force); 80 | subdir.Delete(); 81 | } 82 | } 83 | } 84 | 85 | public static new CaseInsensitiveList Aliases 86 | { 87 | get { return new CaseInsensitiveList() { "Remove-Item", "del", "erase", "rd", "ri", "rm", "rmdir" }; } 88 | } 89 | 90 | public static new ArgumentList SupportedArguments 91 | { 92 | get 93 | { 94 | return new ArgumentList() 95 | { 96 | new StringArgument("Path"), 97 | new BoolArgument("Force"), 98 | new BoolArgument("Recurse") 99 | }; 100 | } 101 | } 102 | 103 | public static new string Synopsis 104 | { 105 | get { return "Deletes files and folders."; } 106 | } 107 | 108 | public static new ExampleEntries Examples 109 | { 110 | get 111 | { 112 | return new ExampleEntries() 113 | { 114 | new ExampleEntry 115 | ( 116 | "Delete a file", 117 | new List() 118 | { 119 | "Remove-Item C:\\tmp\\MyFile.txt", 120 | "rm C:\\tmp\\MyFile.txt" 121 | } 122 | ), 123 | new ExampleEntry("Delete a read-only file", "Remove-Item -Force C:\\Tmp\\MyFile.txt"), 124 | new ExampleEntry("Recursively delete a folder", "Remove-Item -Recurse C:\\Tmp\\MyTools\\") 125 | }; 126 | } 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/SetClipboardCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Windows.Forms; 6 | 7 | /* 8 | Author: @bitsadmin 9 | Website: https://github.com/bitsadmin 10 | License: BSD 3-Clause 11 | */ 12 | 13 | namespace NoPowerShell.Commands.Management 14 | { 15 | public class SetClipboardCommand : PSCommand 16 | { 17 | public SetClipboardCommand(string[] userArguments) : base(userArguments, SupportedArguments) 18 | { 19 | } 20 | 21 | public override CommandResult Execute(CommandResult pipeIn) 22 | { 23 | // Obtain cmdlet parameters 24 | bool append = _arguments.Get("Append").Value; 25 | string value = _arguments.Get("Value").Value; 26 | bool passthru = _arguments.Get("PassThru").Value; 27 | 28 | string contents = GetContents(pipeIn, value); 29 | 30 | if (append) 31 | { 32 | string currentText = Clipboard.GetText(); 33 | currentText += contents; 34 | contents = currentText; 35 | } 36 | 37 | if (string.IsNullOrEmpty(contents)) 38 | Clipboard.Clear(); 39 | else 40 | Clipboard.SetText(contents); 41 | 42 | // Set clipboard contents as result if the -PassThru parameter is provided 43 | // Otherwise simply the empty _results set will be returned 44 | if (passthru) 45 | { 46 | _results = new CommandResult(1) 47 | { 48 | new ResultRecord(1) 49 | { 50 | { "Data", contents } 51 | } 52 | }; 53 | } 54 | 55 | return _results; 56 | } 57 | 58 | private string GetContents(CommandResult pipeIn, string value) 59 | { 60 | string pipeAsString = PipelineHelper.PipeToString(pipeIn); 61 | 62 | if (!string.IsNullOrEmpty(pipeAsString)) 63 | { 64 | if (!string.IsNullOrEmpty(value)) 65 | throw new NoPowerShellException("Either use pipeline input or parameter input, not both"); 66 | 67 | return pipeAsString; 68 | } 69 | else 70 | return value; 71 | } 72 | 73 | public static new CaseInsensitiveList Aliases 74 | { 75 | get { return new CaseInsensitiveList() { "Set-Clipboard", "scb" }; } 76 | } 77 | 78 | public static new ArgumentList SupportedArguments 79 | { 80 | get 81 | { 82 | return new ArgumentList() 83 | { 84 | new StringArgument("Value"), 85 | new BoolArgument("Append", false), 86 | new BoolArgument("PassThru", false) 87 | }; 88 | } 89 | } 90 | 91 | public static new string Synopsis 92 | { 93 | get { return "Sets the current Windows clipboard entry."; } 94 | } 95 | 96 | public static new ExampleEntries Examples 97 | { 98 | get 99 | { 100 | return new ExampleEntries() 101 | { 102 | new ExampleEntry 103 | ( 104 | "Put string on clipboard", 105 | new List() 106 | { 107 | "Set-Clipboard -Value \"You have been PWNED!\"", 108 | "scb \"You have been PWNED!\"" 109 | } 110 | ), 111 | new ExampleEntry("Clear the clipboard", "Set-Clipboard"), 112 | new ExampleEntry("Place output of command on clipboard", "Get-Process | Set-Clipboard") 113 | }; 114 | } 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Management/StopProcessCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Diagnostics; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Management 13 | { 14 | public class StopProcessCommand : PSCommand 15 | { 16 | public StopProcessCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | string Ids = _arguments.Get("Id").Value; 23 | string[] processIds = null; 24 | if (Ids != null) 25 | processIds = Ids.Split(','); 26 | bool force = _arguments.Get("Force").Value; 27 | 28 | // If no IDs are provided via the commandline, check incoming pipe 29 | // In this case Get-Process can be used 30 | if(processIds == null) 31 | { 32 | processIds = new string[pipeIn.Count]; 33 | int i = 0; 34 | foreach(ResultRecord r in pipeIn) 35 | { 36 | processIds[i] = r["ProcessId"]; 37 | i++; 38 | } 39 | } 40 | 41 | // Convert string array to int array 42 | int[] processIdsInt = Array.ConvertAll(processIds, int.Parse); 43 | 44 | // Shutdown/kill processes 45 | foreach (int processId in processIdsInt) 46 | { 47 | Process processToKill = Process.GetProcessById(processId); 48 | 49 | if (force) 50 | processToKill.Kill(); 51 | else 52 | processToKill.CloseMainWindow(); 53 | } 54 | 55 | return null; 56 | } 57 | 58 | public static new CaseInsensitiveList Aliases 59 | { 60 | get { return new CaseInsensitiveList() { "Stop-Process", "kill", "spps" }; } 61 | } 62 | 63 | public static new ArgumentList SupportedArguments 64 | { 65 | get 66 | { 67 | return new ArgumentList() 68 | { 69 | new StringArgument("Id"), 70 | new BoolArgument("Force") 71 | }; 72 | } 73 | } 74 | 75 | public static new string Synopsis 76 | { 77 | get { return "Stops one or more running processes."; } 78 | } 79 | 80 | public static new ExampleEntries Examples 81 | { 82 | get 83 | { 84 | return new ExampleEntries() 85 | { 86 | new ExampleEntry("Gracefully stop processes" , "Stop-Process -Id 4512,7241"), 87 | new ExampleEntry("Kill process" , "Stop-Process -Force -Id 4512"), 88 | new ExampleEntry("Kill all cmd.exe processes", "Get-Process cmd | Stop-Process -Force") 89 | }; 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/NetTCPIP/GetNetIPAddressCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.NetTCPIP 12 | { 13 | public class GetNetIPAddress : PSCommand 14 | { 15 | public GetNetIPAddress(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | bool all = _arguments.Get("All").Value; 22 | 23 | string simpleSelect = "Description, IPAddress, DefaultIPGateway"; 24 | string allSelect = simpleSelect + ", DNSServerSearchOrder"; 25 | string query = "Select {0} From Win32_NetworkAdapterConfiguration {1}"; 26 | 27 | if (all) 28 | query = string.Format(query, allSelect, string.Empty); 29 | else 30 | query = string.Format(query, simpleSelect, "Where IPEnabled = 'True'"); 31 | 32 | _results = WmiHelper.ExecuteWmiQuery(query, computername, username, password); 33 | 34 | return _results; 35 | } 36 | 37 | public static new CaseInsensitiveList Aliases 38 | { 39 | get { 40 | return new CaseInsensitiveList() 41 | { 42 | "Get-NetIPAddress", "ipconfig", 43 | "ifconfig" // Not official 44 | }; 45 | } 46 | } 47 | 48 | public static new ArgumentList SupportedArguments 49 | { 50 | get 51 | { 52 | return new ArgumentList() 53 | { 54 | new BoolArgument("All") 55 | }; 56 | } 57 | } 58 | 59 | public static new string Synopsis 60 | { 61 | get { return "Gets the IP address configuration."; } 62 | } 63 | 64 | public static new ExampleEntries Examples 65 | { 66 | get 67 | { 68 | return new ExampleEntries() 69 | { 70 | new ExampleEntry 71 | ( 72 | "Show network interfaces", 73 | new List() 74 | { 75 | "Get-NetIPAddress", 76 | "ipconfig", 77 | "ifconfig" 78 | } 79 | ), 80 | new ExampleEntry 81 | ( 82 | "Show all network interfaces", 83 | new List() 84 | { 85 | "Get-NetIPAddress -All", 86 | "ipconfig -All" 87 | } 88 | ), 89 | new ExampleEntry 90 | ( 91 | "Show all network interfaces on a remote machine using WMI", 92 | new List() 93 | { 94 | "Get-NetIPAddress -All -ComputerName MyServer -Username MyUser -Password MyPassword", 95 | "Get-NetIPAddress -All -ComputerName MyServer" 96 | } 97 | ) 98 | }; 99 | } 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/NetTCPIP/GetNetRouteCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.NetTCPIP 12 | { 13 | public class GetNetRouteCommand : PSCommand 14 | { 15 | public GetNetRouteCommand(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | // Collect the (optional) ComputerName, Username and Password parameters 22 | base.Execute(); 23 | 24 | _results = WmiHelper.ExecuteWmiQuery("Select Caption, Description, Destination, Mask, NextHop From Win32_IP4RouteTable", computername, username, password); 25 | 26 | return _results; 27 | } 28 | 29 | public static new CaseInsensitiveList Aliases 30 | { 31 | get { 32 | return new CaseInsensitiveList() 33 | { 34 | "Get-NetRoute", 35 | "route" // Not official 36 | }; 37 | } 38 | } 39 | 40 | public static new ArgumentList SupportedArguments 41 | { 42 | get 43 | { 44 | return new ArgumentList() 45 | { 46 | }; 47 | } 48 | } 49 | 50 | public static new string Synopsis 51 | { 52 | get { return "Gets the IP route information from the IP routing table."; } 53 | } 54 | 55 | public static new ExampleEntries Examples 56 | { 57 | get 58 | { 59 | return new ExampleEntries() 60 | { 61 | new ExampleEntry 62 | ( 63 | "Show the IP routing table", 64 | new List() 65 | { 66 | "Get-NetRoute", 67 | "route" 68 | } 69 | ), 70 | new ExampleEntry 71 | ( 72 | "Show the IP routing table on a remote machine using WMI", 73 | new List() 74 | { 75 | "Get-NetRoute -ComputerName MyServer -Username MyUser -Password MyPassword", 76 | "route -ComputerName MyServer" 77 | } 78 | ) 79 | }; 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/NetTCPIP/GetNetTCPConnectionCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.NetTCPIP 13 | { 14 | public class GetNetTCPConnectionCommand : PSCommand 15 | { 16 | public GetNetTCPConnectionCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Collect the (optional) ComputerName, Username and Password parameters 23 | base.Execute(); 24 | 25 | // Perform query 26 | _results = WmiHelper.ExecuteWmiQuery("Root\\StandardCimv2", "Select LocalAddress, LocalPort, OwningProcess, RemoteAddress, RemotePort, State From MSFT_NetTCPConnection", computername, username, password); 27 | 28 | return _results; 29 | } 30 | 31 | public static new CaseInsensitiveList Aliases 32 | { 33 | get 34 | { 35 | return new CaseInsensitiveList() 36 | { 37 | "Get-GetNetTCPConnection", 38 | "netstat" // unofficial 39 | }; 40 | } 41 | } 42 | 43 | public static new ArgumentList SupportedArguments 44 | { 45 | get 46 | { 47 | return new ArgumentList() 48 | { 49 | }; 50 | } 51 | } 52 | 53 | public static new string Synopsis 54 | { 55 | get { return "Gets TCP connections."; } 56 | } 57 | 58 | public static new ExampleEntries Examples 59 | { 60 | get 61 | { 62 | return new ExampleEntries() 63 | { 64 | new ExampleEntry 65 | ( 66 | "Show TCP connections on the local machine", 67 | new List() 68 | { 69 | "Get-NetTCPConnection", 70 | "netstat" 71 | } 72 | ), 73 | new ExampleEntry("Show TCP connections on a remote machine", "Get-NetTCPConnection -ComputerName MyServer"), 74 | }; 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/SmbShare/GetSmbMappingCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.SmbShare 12 | { 13 | public class GetSmbMapping : PSCommand 14 | { 15 | public GetSmbMapping(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | _results = WmiHelper.ExecuteWmiQuery(@"ROOT\Microsoft\Windows\SMB", "Select LocalPath,RemotePath From MSFT_SmbMapping", computername, username, password); 22 | return _results; 23 | } 24 | 25 | public static new CaseInsensitiveList Aliases 26 | { 27 | get { 28 | return new CaseInsensitiveList() 29 | { 30 | "Get-SmbMapping", 31 | "netuse" // Not official 32 | }; 33 | } 34 | } 35 | 36 | public static new ArgumentList SupportedArguments 37 | { 38 | get 39 | { 40 | return new ArgumentList() 41 | { 42 | }; 43 | } 44 | } 45 | 46 | public static new string Synopsis 47 | { 48 | get { return "Retrieves the SMB client directory mappings created for a server."; } 49 | } 50 | 51 | public static new ExampleEntries Examples 52 | { 53 | get 54 | { 55 | return new ExampleEntries() 56 | { 57 | new ExampleEntry 58 | ( 59 | "List network shares on the local machine that are exposed to the network", 60 | new List() 61 | { 62 | "Get-SmbMapping", 63 | "netuse" 64 | } 65 | ) 66 | }; 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/SmbShare/GetSmbShareCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | 4 | /* 5 | Author: @bitsadmin 6 | Website: https://github.com/bitsadmin 7 | License: BSD 3-Clause 8 | */ 9 | 10 | namespace NoPowerShell.Commands.SmbShare 11 | { 12 | public class GetSmbShareCommand : PSCommand 13 | { 14 | public GetSmbShareCommand(string[] userArguments) : base(userArguments, SupportedArguments) 15 | { 16 | } 17 | 18 | public override CommandResult Execute(CommandResult pipeIn) 19 | { 20 | _results = WmiHelper.ExecuteWmiQuery("Select * From Win32_Share", computername, username, password); 21 | return _results; 22 | } 23 | 24 | public static new CaseInsensitiveList Aliases 25 | { 26 | get { 27 | return new CaseInsensitiveList() 28 | { 29 | "Get-SmbShare", 30 | "netshare" // Not official 31 | }; 32 | } 33 | } 34 | 35 | public static new ArgumentList SupportedArguments 36 | { 37 | get 38 | { 39 | return new ArgumentList() 40 | { 41 | }; 42 | } 43 | } 44 | 45 | public static new string Synopsis 46 | { 47 | get { return "Retrieves the SMB shares on the computer."; } 48 | } 49 | 50 | public static new ExampleEntries Examples 51 | { 52 | get 53 | { 54 | return new ExampleEntries() 55 | { 56 | new ExampleEntry("List SMB shares on the computer", "Get-SmbShare"), 57 | }; 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/TemplateCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands 13 | { 14 | public class TemplateCommand : PSCommand 15 | { 16 | public TemplateCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | // Collect the (optional) ComputerName, Username and Password parameters 23 | base.Execute(); 24 | 25 | // Obtain cmdlet parameters 26 | // Will contain all of the arguments from the 'ArgumentList Arguments' below 27 | bool myFlag = _arguments.Get("MyFlag").Value; 28 | int myInteger = _arguments.Get("MyInteger").Value; 29 | string myString = _arguments.Get("MyString").Value; 30 | 31 | // Write your code here, storing the output in attributename-value pairs 32 | // Example of resulting table: 33 | // Attribute1 Attribute2 34 | // ---------- ---------- 35 | // Line00-Attribute1-Hello World Line00-Attribute2-Hello World 36 | // Line01-Attribute1-Hello World Line01-Attribute2-Hello World 37 | // Line02-Attribute1-Hello World Line02-Attribute2-Hello World 38 | // Line03-Attribute1-Hello World Line03-Attribute2-Hello World 39 | // Line04-Attribute1-Hello World Line04-Attribute2-Hello World 40 | // etc. 41 | 42 | if (!myFlag) 43 | { 44 | for (int i = 0; i < myInteger; i++) 45 | { 46 | _results.Add( 47 | new ResultRecord() 48 | { 49 | { "Attribute1", string.Format("Line{0:D2}-Attribute1-{1}", i, myString) }, 50 | { "Attribute2", string.Format("Line{0:D2}-Attribute2-{1}", i, myString) } 51 | //{ "AttributeN", string.Format("Line{0}-AttributeN-{1}", i, myString) } 52 | } 53 | ); 54 | } 55 | } 56 | else 57 | { 58 | _results.Add( 59 | new ResultRecord() 60 | { 61 | { string.Empty, "MyFlag flag has been set." } 62 | } 63 | ); 64 | } 65 | 66 | // Always return the results so the output can be used by the next command in the pipeline 67 | return _results; 68 | } 69 | 70 | public static new CaseInsensitiveList Aliases 71 | { 72 | get { return new CaseInsensitiveList() { "Get-TemplateCommand", "gtc" }; } 73 | } 74 | 75 | public static new ArgumentList SupportedArguments 76 | { 77 | get 78 | { 79 | return new ArgumentList() 80 | { 81 | new BoolArgument("MyFlag"), 82 | new IntegerArgument("MyInteger", 5, true), 83 | new StringArgument("MyString", "Hello World") 84 | }; 85 | } 86 | } 87 | 88 | public static new string Synopsis 89 | { 90 | get { return "This template shows how easy it is to develop new NoPowerShell cmdlets."; } 91 | } 92 | 93 | public static new ExampleEntries Examples 94 | { 95 | get 96 | { 97 | return new ExampleEntries() 98 | { 99 | new ExampleEntry("These entries show up when executing the 'Get-Help Get-TemplateCommand' command", "Get-TemplateCommand -MyFlag"), 100 | new ExampleEntry 101 | ( 102 | "This is another example with two related or equivalent examples", 103 | new List() 104 | { 105 | "gtc \"Bye PowerShell\" -MyInteger 30 | ? Attribute2 -Like Line1* | select Attribute2 | fl", 106 | "Get-TemplateCommand -MyInteger 10 \"Bye PowerShell\"" 107 | } 108 | ) 109 | }; 110 | } 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/ExportCsvCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | using System.IO; 6 | 7 | /* 8 | Author: @bitsadmin 9 | Website: https://github.com/bitsadmin 10 | License: BSD 3-Clause 11 | */ 12 | 13 | namespace NoPowerShell.Commands.Utility 14 | { 15 | public class ExportCsvCommand : PSCommand 16 | { 17 | public ExportCsvCommand(string[] arguments) : base(arguments, SupportedArguments) 18 | { 19 | } 20 | 21 | public override CommandResult Execute(CommandResult pipeIn) 22 | { 23 | string path = _arguments.Get("Path").Value; 24 | string encodingstr = _arguments.Get("Encoding").Value; 25 | 26 | if (pipeIn == null || pipeIn.Count == 0) 27 | return null; 28 | 29 | // Determine encoding 30 | Encoding encoding = Encoding.GetEncoding(encodingstr); 31 | 32 | // Initialize output 33 | string[] outlines = new string[pipeIn.Count + 1]; 34 | int currentLine = 0; 35 | 36 | // Compile header 37 | string[] columns = new string[pipeIn[0].Count]; 38 | int i = 0; 39 | foreach(KeyValuePair col in pipeIn[0]) 40 | { 41 | columns[i] = col.Key; 42 | i++; 43 | } 44 | outlines[currentLine] = string.Format("\"{0}\"", (string.Join("\",\"", columns))); 45 | currentLine++; 46 | 47 | // Compile records 48 | foreach (ResultRecord result in pipeIn) 49 | { 50 | // Collect values 51 | string[] values = new string[result.Count]; 52 | i = 0; 53 | foreach(KeyValuePair kvp in result) 54 | { 55 | // Escape quote by double quotes 56 | values[i] = kvp.Value.Replace("\"", "\"\""); 57 | i++; 58 | } 59 | 60 | // Store values 61 | outlines[currentLine] = string.Format("\"{0}\"", (string.Join("\",\"", values))); 62 | currentLine++; 63 | } 64 | 65 | // Save to file with specified encoding 66 | File.WriteAllLines(path, outlines, encoding); 67 | 68 | return null; 69 | } 70 | 71 | public static new CaseInsensitiveList Aliases 72 | { 73 | get { return new CaseInsensitiveList() { "Export-Csv", "epcsv" }; } 74 | } 75 | 76 | public static new ArgumentList SupportedArguments 77 | { 78 | get 79 | { 80 | return new ArgumentList() 81 | { 82 | new StringArgument("Path"), 83 | new StringArgument("Encoding", "Unicode") 84 | }; 85 | } 86 | } 87 | 88 | public static new string Synopsis 89 | { 90 | get { return "Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file."; } 91 | } 92 | 93 | public static new ExampleEntries Examples 94 | { 95 | get 96 | { 97 | return new ExampleEntries() 98 | { 99 | new ExampleEntry("Store list of commands as CSV", @"Get-Command | Export-Csv -Encoding ASCII -Path commands.csv"), 100 | }; 101 | } 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/FormatListCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.Utility 12 | { 13 | public class FormatListCommand : PSCommand 14 | { 15 | public FormatListCommand(string[] arguments) : base(arguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | string[] properties = _arguments.Get("Property").Value.Split(','); 22 | 23 | _results.Output = CommandResult.OutputType.List; 24 | 25 | if (pipeIn == null) 26 | return null; 27 | 28 | foreach (ResultRecord result in pipeIn) 29 | { 30 | // Show all columns 31 | if (properties[0] == string.Empty) 32 | _results.Add(result); 33 | 34 | // Show only specific columns 35 | else 36 | { 37 | ResultRecord newResult = new ResultRecord(); 38 | 39 | foreach (string attr in properties) 40 | { 41 | if (result.ContainsKey(attr)) 42 | newResult.Add(attr, result[attr]); 43 | else 44 | newResult.Add(attr, null); 45 | } 46 | 47 | _results.Add(newResult); 48 | } 49 | } 50 | 51 | ResultPrinter.OutputResults(_results); 52 | 53 | return _results; 54 | } 55 | 56 | public static new CaseInsensitiveList Aliases 57 | { 58 | get { return new CaseInsensitiveList() { "Format-List", "fl" }; } 59 | } 60 | 61 | public static new ArgumentList SupportedArguments 62 | { 63 | get 64 | { 65 | return new ArgumentList() 66 | { 67 | new StringArgument("Property", string.Empty) 68 | }; 69 | } 70 | } 71 | 72 | public static new string Synopsis 73 | { 74 | get { return "Formats the output as a list of properties in which each property appears on a new line."; } 75 | } 76 | 77 | public static new ExampleEntries Examples 78 | { 79 | get 80 | { 81 | return new ExampleEntries() 82 | { 83 | new ExampleEntry 84 | ( 85 | "Format output as a list", 86 | new List() 87 | { 88 | "Get-LocalUser | Format-List", 89 | "Get-LocalUser | fl" 90 | } 91 | ), 92 | new ExampleEntry("Format output as a list showing only specific attributes", "Get-LocalUser | fl Name,Description"), 93 | }; 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/FormatTableCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.Utility 12 | { 13 | public class FormatTableCommand : PSCommand 14 | { 15 | public FormatTableCommand(string[] arguments) : base(arguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | string[] properties = _arguments.Get("Property").Value.Split(','); 22 | 23 | _results.Output = CommandResult.OutputType.Table; 24 | 25 | if (pipeIn == null) 26 | return null; 27 | 28 | foreach (ResultRecord result in pipeIn) 29 | { 30 | // Show all columns 31 | if (properties[0] == string.Empty) 32 | _results.Add(result); 33 | 34 | // Show only specific columns 35 | else 36 | { 37 | ResultRecord newResult = new ResultRecord(); 38 | 39 | foreach (string attr in properties) 40 | { 41 | if (result.ContainsKey(attr)) 42 | newResult.Add(attr, result[attr]); 43 | else 44 | newResult.Add(attr, null); 45 | } 46 | 47 | _results.Add(newResult); 48 | } 49 | } 50 | 51 | ResultPrinter.OutputResults(_results); 52 | 53 | return _results; 54 | } 55 | 56 | public static new CaseInsensitiveList Aliases 57 | { 58 | get { return new CaseInsensitiveList() { "Format-Table", "ft" }; } 59 | } 60 | 61 | public static new ArgumentList SupportedArguments 62 | { 63 | get 64 | { 65 | return new ArgumentList() 66 | { 67 | new StringArgument("Property", string.Empty) 68 | }; 69 | } 70 | } 71 | 72 | public static new string Synopsis 73 | { 74 | get { return "Formats the output as a table."; } 75 | } 76 | 77 | public static new ExampleEntries Examples 78 | { 79 | get 80 | { 81 | return new ExampleEntries() 82 | { 83 | new ExampleEntry 84 | ( 85 | "Format output as a table", 86 | new List() 87 | { 88 | "Get-Process | Format-Table", 89 | "Get-Process | ft" 90 | } 91 | ), 92 | new ExampleEntry("Format output as a table showing only specific attributes", "Get-Process | ft ProcessId,Name"), 93 | }; 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/InvokeWebRequestCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Net; 7 | 8 | /* 9 | Author: @bitsadmin 10 | Website: https://github.com/bitsadmin 11 | License: BSD 3-Clause 12 | */ 13 | 14 | namespace NoPowerShell.Commands.Utility 15 | { 16 | public class InvokeWebRequest : PSCommand 17 | { 18 | public InvokeWebRequest(string[] userArguments) : base(userArguments, SupportedArguments) 19 | { 20 | } 21 | 22 | public override CommandResult Execute(CommandResult pipeIn) 23 | { 24 | string uri = _arguments.Get("URI").Value; 25 | string outfile = _arguments.Get("OutFile").Value; 26 | 27 | // Try to automatically determine filename 28 | if (string.IsNullOrEmpty(outfile)) 29 | { 30 | Uri href = new Uri(uri); 31 | outfile = Path.GetFileName(href.LocalPath); 32 | } 33 | 34 | // If still empty, use "out" as filename 35 | if (string.IsNullOrEmpty(outfile)) 36 | outfile = "out"; 37 | 38 | // Known issues: 39 | // - TLS 1.1+ is not supported by .NET Framework 2, so any site enforcing it will result in a connection error 40 | using (WebClient client = new WebClient()) 41 | { 42 | client.DownloadFile(uri, outfile); 43 | } 44 | 45 | return _results; 46 | } 47 | 48 | public static new CaseInsensitiveList Aliases 49 | { 50 | get { return new CaseInsensitiveList() { "Invoke-WebRequest", "curl", "iwr", "wget" }; } 51 | } 52 | 53 | public static new ArgumentList SupportedArguments 54 | { 55 | get 56 | { 57 | return new ArgumentList() 58 | { 59 | new StringArgument("URI"), 60 | new StringArgument("OutFile", true) 61 | }; 62 | } 63 | } 64 | 65 | public static new string Synopsis 66 | { 67 | get { return "Gets content from a web page on the Internet."; } 68 | } 69 | 70 | public static new ExampleEntries Examples 71 | { 72 | get 73 | { 74 | return new ExampleEntries() 75 | { 76 | new ExampleEntry( 77 | "Download file from the Internet", 78 | new List() 79 | { 80 | "Invoke-WebRequest http://myserver.me/nc.exe", 81 | "wget http://myserver.me/nc.exe" 82 | } 83 | ), 84 | new ExampleEntry("Download file from the Internet specifying the destination", "wget http://myserver.me/nc.exe -OutFile C:\\Tmp\\netcat.exe"), 85 | }; 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/MeasureObjectCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.Utility 12 | { 13 | public class MeasureObjectCommand : PSCommand 14 | { 15 | public MeasureObjectCommand(string[] userArguments) : base(userArguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | int count = -1; 22 | 23 | // Count lines if one block of output 24 | if(pipeIn.Count == 1 && pipeIn[0].Keys.Count == 1 && pipeIn[0].ContainsKey(string.Empty)) 25 | { 26 | string blob = pipeIn[0][string.Empty]; 27 | count = blob.Split('\n').Length; 28 | } 29 | // Count number of records 30 | else 31 | { 32 | count = pipeIn.Count; 33 | } 34 | 35 | _results.Add( 36 | new ResultRecord() 37 | { 38 | { "Count", count.ToString() } 39 | } 40 | ); 41 | 42 | return _results; 43 | } 44 | 45 | public static new CaseInsensitiveList Aliases 46 | { 47 | get { return new CaseInsensitiveList() { "Measure-Object", "measure" }; } 48 | } 49 | 50 | public static new ArgumentList SupportedArguments 51 | { 52 | get 53 | { 54 | return new ArgumentList() 55 | { 56 | }; 57 | } 58 | } 59 | 60 | public static new string Synopsis 61 | { 62 | get { return "Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text."; } 63 | } 64 | 65 | public static new ExampleEntries Examples 66 | { 67 | get 68 | { 69 | return new ExampleEntries() 70 | { 71 | new ExampleEntry 72 | ( 73 | "Count number of results", 74 | new List() 75 | { 76 | "Get-Process | Measure-Object", 77 | "Get-Process | measure" 78 | } 79 | ), 80 | new ExampleEntry("Count number of lines in file", "gc C:\\Windows\\WindowsUpdate.log | measure"), 81 | }; 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/OutFileCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | 7 | /* 8 | Author: @bitsadmin 9 | Website: https://github.com/bitsadmin 10 | License: BSD 3-Clause 11 | */ 12 | 13 | namespace NoPowerShell.Commands.Utility 14 | { 15 | public class OutFileCommand : PSCommand 16 | { 17 | public OutFileCommand(string[] userArguments) : base(userArguments, SupportedArguments) 18 | { 19 | } 20 | 21 | public override CommandResult Execute(CommandResult pipeIn) 22 | { 23 | string filePath = _arguments.Get("FilePath").Value; 24 | string encoding = _arguments.Get("Encoding").Value; 25 | bool passthru = _arguments.Get("PassThru").Value; 26 | 27 | Encoding encodingType = Encoding.GetEncoding(encoding); 28 | 29 | // Serialize object to string 30 | string pipeAsString = PipelineHelper.PipeToString(pipeIn); 31 | 32 | // Ignore if empty 33 | if (string.IsNullOrEmpty(pipeAsString)) 34 | return _results; 35 | 36 | // Store in file 37 | File.WriteAllText(filePath, pipeAsString, encodingType); 38 | 39 | // Empty result because it is written to a file 40 | if (passthru) 41 | _results = pipeIn; 42 | 43 | return _results; 44 | } 45 | 46 | public static new CaseInsensitiveList Aliases 47 | { 48 | get { return new CaseInsensitiveList() { "Out-File" }; } 49 | } 50 | 51 | public static new ArgumentList SupportedArguments 52 | { 53 | get 54 | { 55 | return new ArgumentList() 56 | { 57 | new StringArgument("FilePath", false), 58 | new StringArgument("Encoding", "UTF-8"), 59 | new BoolArgument("PassThru", false) 60 | }; 61 | } 62 | } 63 | 64 | public static new string Synopsis 65 | { 66 | get { return "Sends output to a file."; } 67 | } 68 | 69 | public static new ExampleEntries Examples 70 | { 71 | get 72 | { 73 | return new ExampleEntries() 74 | { 75 | new ExampleEntry("Echo string to the console", "echo \"Hello Console!\""), 76 | new ExampleEntry 77 | ( 78 | "Create file hello.txt on the C: drive containing the \"Hello World!\" ASCII string", 79 | new List() 80 | { 81 | @"Write-Output ""Hello World!"" | Out-File -Encoding ASCII C:\hello.txt", 82 | @"echo ""Hello World!"" | Out-File -Encoding ASCII C:\hello.txt" 83 | } 84 | ) 85 | }; 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/SelectObjectCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System.Collections.Generic; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.Commands.Utility 12 | { 13 | public class SelectObjectCommand : PSCommand 14 | { 15 | public SelectObjectCommand(string[] arguments) : base(arguments, SupportedArguments) 16 | { 17 | } 18 | 19 | public override CommandResult Execute(CommandResult pipeIn) 20 | { 21 | string[] attributes = _arguments.Get("Property").Value.Split(','); 22 | int first = _arguments.Get("First").Value; 23 | 24 | if (pipeIn == null) 25 | return null; 26 | 27 | bool wildcardSelect = attributes[0] == "*"; 28 | bool firstSet = first > 0; 29 | 30 | // Simply return pipeIn if empty 31 | if (pipeIn.Count == 0) 32 | return pipeIn; 33 | 34 | // Ignore casing 35 | List correctAttributes = new List(); 36 | foreach(string inputAttr in attributes) 37 | { 38 | bool found = false; 39 | 40 | // Locate case-insensitive match 41 | foreach (string key in pipeIn[0].Keys) 42 | { 43 | if(inputAttr.Equals(key, System.StringComparison.InvariantCultureIgnoreCase)) 44 | { 45 | correctAttributes.Add(key); 46 | found = true; 47 | break; 48 | } 49 | } 50 | 51 | // Add original non-existent column if no matching column found 52 | if (!found) 53 | correctAttributes.Add(inputAttr); 54 | } 55 | attributes = correctAttributes.ToArray(); 56 | 57 | int counter = 0; 58 | foreach (ResultRecord result in pipeIn) 59 | { 60 | // Obey -First [int32] parameter and break if number is reached 61 | if (firstSet && counter == first) 62 | break; 63 | 64 | // If all attributes need to be taken 65 | if (wildcardSelect) 66 | { 67 | _results.Add(result); 68 | } 69 | // If specific attributes are selected 70 | else 71 | { 72 | ResultRecord newResult = new ResultRecord(); 73 | 74 | foreach (string attr in attributes) 75 | { 76 | if (result.ContainsKey(attr)) 77 | newResult.Add(attr, result[attr]); 78 | else 79 | newResult.Add(attr, null); 80 | } 81 | 82 | _results.Add(newResult); 83 | } 84 | 85 | counter++; 86 | } 87 | 88 | return _results; 89 | } 90 | 91 | public static new CaseInsensitiveList Aliases 92 | { 93 | get { return new CaseInsensitiveList() { "Select-Object", "select" }; } 94 | } 95 | 96 | public static new ArgumentList SupportedArguments 97 | { 98 | get 99 | { 100 | return new ArgumentList() 101 | { 102 | new StringArgument("Property", "*", false), 103 | new IntegerArgument("First", 0, true) 104 | }; 105 | } 106 | } 107 | 108 | public static new string Synopsis 109 | { 110 | get { return "Selects objects or object properties."; } 111 | } 112 | 113 | public static new ExampleEntries Examples 114 | { 115 | get 116 | { 117 | return new ExampleEntries() 118 | { 119 | new ExampleEntry("Show only the Name in a file listing", "ls C:\\ | select Name"), 120 | new ExampleEntry("Show first 10 results of file listing", "ls C:\\Windows\\System32 -Include *.exe | select -First 10 Name,Length") 121 | }; 122 | } 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/SortObjectCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | 4 | /* 5 | Author: @bitsadmin 6 | Website: https://github.com/bitsadmin 7 | License: BSD 3-Clause 8 | */ 9 | 10 | namespace NoPowerShell.Commands.Utility 11 | { 12 | public class SortObjectCommand : PSCommand 13 | { 14 | public SortObjectCommand(string[] userArguments) : base(userArguments, SupportedArguments) 15 | { 16 | } 17 | 18 | public override CommandResult Execute(CommandResult pipeIn) 19 | { 20 | string property = _arguments.Get("Property").Value; 21 | bool descending = _arguments.Get("Descending").Value; 22 | bool unique = _arguments.Get("Unique").Value; 23 | 24 | // Finished if input pipe is empty 25 | if (pipeIn.Count == 0) 26 | return pipeIn; 27 | 28 | // If no specific field specified, use first one 29 | if (string.IsNullOrEmpty(property)) 30 | { 31 | foreach (string field in pipeIn[0].Keys) 32 | { 33 | property = field; 34 | break; 35 | } 36 | } 37 | 38 | // Validate if property exists 39 | if (!pipeIn[0].ContainsKey(property)) 40 | throw new NoPowerShellException("Attribute \"{0}\" does not exist", property); 41 | 42 | // Perform sort 43 | if(descending) 44 | pipeIn.Sort((x, y) => y[property].CompareTo(x[property])); 45 | else 46 | pipeIn.Sort((x, y) => x[property].CompareTo(y[property])); 47 | 48 | // Perform unique if specified 49 | if(unique) 50 | { 51 | CommandResult pipeOut = new CommandResult(); 52 | 53 | int r1i = 0; 54 | bool first = true; 55 | foreach (ResultRecord r1 in pipeIn) 56 | { 57 | // First record is always unique 58 | if(first) 59 | { 60 | first = false; 61 | pipeOut.Add(r1); 62 | r1i++; 63 | continue; 64 | } 65 | 66 | int r2i = 0; 67 | bool foundDuplicate = false; 68 | foreach (ResultRecord r2 in pipeIn) 69 | { 70 | // Don't compare with yourself 71 | if (r1i == r2i) 72 | { 73 | r2i++; 74 | continue; 75 | } 76 | 77 | // Compare objects or property 78 | if ( 79 | // Unique on full object 80 | (string.IsNullOrEmpty(property) && r1.Equals(r2)) 81 | || 82 | // Unique on specific property 83 | (!string.IsNullOrEmpty(property) && r1[property] == r2[property]) 84 | ) 85 | { 86 | foundDuplicate = true; 87 | break; 88 | } 89 | 90 | r2i++; 91 | } 92 | 93 | // Add if not found twice 94 | if (!foundDuplicate) 95 | pipeOut.Add(r1); 96 | 97 | r1i++; 98 | } 99 | 100 | return pipeOut; 101 | } 102 | 103 | return pipeIn; 104 | } 105 | 106 | public static new CaseInsensitiveList Aliases 107 | { 108 | get { return new CaseInsensitiveList() { "Sort-Object", "sort" }; } 109 | } 110 | 111 | public static new ArgumentList SupportedArguments 112 | { 113 | get 114 | { 115 | return new ArgumentList() 116 | { 117 | new StringArgument("Property"), 118 | new BoolArgument("Descending", false), 119 | new BoolArgument("Unique", false) 120 | }; 121 | } 122 | } 123 | 124 | public static new string Synopsis 125 | { 126 | get { return "Sorts objects by property values."; } 127 | } 128 | 129 | public static new ExampleEntries Examples 130 | { 131 | get 132 | { 133 | return new ExampleEntries() 134 | { 135 | new ExampleEntry("Sort processes by name descending", "ps | sort -d name") 136 | }; 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Commands/Utility/WriteOutputCommand.cs: -------------------------------------------------------------------------------- 1 | using NoPowerShell.Arguments; 2 | using NoPowerShell.HelperClasses; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.Commands.Utility 13 | { 14 | public class WriteOutputCommand : PSCommand 15 | { 16 | public WriteOutputCommand(string[] userArguments) : base(userArguments, SupportedArguments) 17 | { 18 | } 19 | 20 | public override CommandResult Execute(CommandResult pipeIn) 21 | { 22 | string inputObject = _arguments.Get("InputObject").Value; 23 | 24 | // Push input string in pipe 25 | _results.Add( 26 | new ResultRecord() 27 | { 28 | { string.Empty, inputObject } 29 | } 30 | ); 31 | 32 | return _results; 33 | } 34 | 35 | public static new CaseInsensitiveList Aliases 36 | { 37 | get { return new CaseInsensitiveList() { "Write-Output", "echo", "write" }; } 38 | } 39 | 40 | public static new ArgumentList SupportedArguments 41 | { 42 | get 43 | { 44 | return new ArgumentList() 45 | { 46 | new StringArgument("InputObject", false) 47 | }; 48 | } 49 | } 50 | 51 | public static new string Synopsis 52 | { 53 | get { return "Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console."; } 54 | } 55 | 56 | public static new ExampleEntries Examples 57 | { 58 | get 59 | { 60 | return new ExampleEntries() 61 | { 62 | new ExampleEntry 63 | ( 64 | "Echo string to the console", 65 | new List() 66 | { 67 | "Write-Output \"Hello World!\"", 68 | "echo \"Hello World!\"" 69 | } 70 | ) 71 | }; 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/CaseInsensitiveList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | /* 5 | Author: @bitsadmin 6 | Website: https://github.com/bitsadmin 7 | License: BSD 3-Clause 8 | */ 9 | 10 | namespace NoPowerShell.HelperClasses 11 | { 12 | public class CaseInsensitiveList : List 13 | { 14 | public new bool Contains(string item) 15 | { 16 | foreach (string s in this) 17 | { 18 | if (s.Equals(item, StringComparison.InvariantCultureIgnoreCase)) 19 | return true; 20 | } 21 | 22 | return false; 23 | } 24 | 25 | public CaseInsensitiveList() : base() 26 | { 27 | } 28 | 29 | public CaseInsensitiveList(IEnumerable collection) : base(collection) 30 | { 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/CommandResult.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | /* 4 | Author: @bitsadmin 5 | Website: https://github.com/bitsadmin 6 | License: BSD 3-Clause 7 | */ 8 | 9 | namespace NoPowerShell.HelperClasses 10 | { 11 | public class CommandResult : List 12 | { 13 | public enum OutputType { List, Table, Auto }; 14 | public OutputType Output { get; set; } 15 | 16 | public CommandResult(int capacity) : base(capacity) 17 | { 18 | Output = OutputType.Auto; 19 | } 20 | 21 | public CommandResult() : base() 22 | { 23 | Output = OutputType.Auto; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/Exceptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.HelperClasses 12 | { 13 | class NoPowerShellException : Exception 14 | { 15 | public NoPowerShellException() : base() 16 | { 17 | } 18 | 19 | public NoPowerShellException(string message) : base(message) 20 | { 21 | } 22 | 23 | public NoPowerShellException(string messageFormat, params object[] args) : base(string.Format(messageFormat, args)) 24 | { 25 | } 26 | } 27 | 28 | class CommandNotFoundException : NoPowerShellException 29 | { 30 | public string Command { get; set; } 31 | public override string Message => string.Format("{0} : The term '{0}' is not recognized as the name of a cmdlet.", Command); 32 | 33 | public CommandNotFoundException(string command) : base() 34 | { 35 | Command = command; 36 | } 37 | } 38 | 39 | class ParameterBindingException : CommandNotFoundException 40 | { 41 | public string Parameter { get; set; } 42 | public override string Message => string.Format("{0} : A parameter cannot be found that matches parameter name '{1}'.", Command, Parameter); 43 | 44 | public ParameterBindingException(string command, string parameter) : base(command) 45 | { 46 | Parameter = parameter; 47 | } 48 | } 49 | 50 | class ItemNotFoundException : NoPowerShellException 51 | { 52 | public string Path { get; set; } 53 | public override string Message => string.Format("Cannot find path '{0}' because it does not exist.", Path); 54 | 55 | public ItemNotFoundException(string path) : base() 56 | { 57 | Path = path; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/HelpEntries.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.HelperClasses 12 | { 13 | public class ExampleEntries : List 14 | { 15 | } 16 | 17 | public class ExampleEntry 18 | { 19 | private string _description; 20 | private List _examples; 21 | 22 | public ExampleEntry(string description, string example) 23 | { 24 | _description = description; 25 | _examples = new List(1) { example }; 26 | } 27 | 28 | public ExampleEntry(string description, List examples) 29 | { 30 | _description = description; 31 | _examples = examples; 32 | } 33 | 34 | public string Description 35 | { 36 | get { return _description; } 37 | } 38 | 39 | public List Examples 40 | { 41 | get { return _examples; } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/PipeParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using NoPowerShell.Commands; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.HelperClasses 12 | { 13 | class PipeParser 14 | { 15 | public static List ParseArguments(string[] args, Dictionary commandTypes) 16 | { 17 | List> parsedPipes = new List>(); 18 | List currentPipe = new List(); 19 | 20 | // Split pipes 21 | foreach (string arg in args) 22 | { 23 | if (arg == "|") 24 | { 25 | parsedPipes.Add(currentPipe); 26 | currentPipe = new List(); 27 | } 28 | else 29 | { 30 | currentPipe.Add(arg); 31 | } 32 | } 33 | parsedPipes.Add(currentPipe); 34 | 35 | // Parse commands between pipes 36 | List allCommands = new List(parsedPipes.Count); 37 | foreach (List pipe in parsedPipes) 38 | { 39 | string command = pipe[0].ToLowerInvariant(); 40 | string[] pipeargs = pipe.GetRange(1, pipe.Count - 1).ToArray(); 41 | 42 | // Locate the command in the aliases of the available commands 43 | bool foundMatchingCommand = false; 44 | foreach (KeyValuePair commandType in commandTypes) 45 | { 46 | if (commandType.Value.Contains(command)) 47 | { 48 | object[] parameters = new object[] { pipeargs }; 49 | try 50 | { 51 | allCommands.Add((PSCommand)Activator.CreateInstance(commandType.Key, parameters)); 52 | } 53 | catch(System.Reflection.TargetInvocationException e) 54 | { 55 | throw e.InnerException; 56 | } 57 | foundMatchingCommand = true; 58 | break; 59 | } 60 | } 61 | 62 | if (!foundMatchingCommand) 63 | throw new CommandNotFoundException(pipe[0]); 64 | } 65 | 66 | return allCommands; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/PipelineHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.HelperClasses 12 | { 13 | class PipelineHelper 14 | { 15 | public static string PipeToString(CommandResult pipeIn) 16 | { 17 | if (pipeIn == null) 18 | return string.Empty; 19 | 20 | List lines = new List(pipeIn.Count); 21 | foreach (ResultRecord r in pipeIn) 22 | { 23 | string[] arr = new string[r.Values.Count]; 24 | r.Values.CopyTo(arr, 0); 25 | string outline = string.Join(" | ", arr); 26 | lines.Add(outline); 27 | } 28 | 29 | return string.Join(System.Environment.NewLine, lines.ToArray()); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/ProviderHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Win32; 3 | 4 | /* 5 | Author: @bitsadmin 6 | Website: https://github.com/bitsadmin 7 | License: BSD 3-Clause 8 | */ 9 | 10 | namespace NoPowerShell.HelperClasses 11 | { 12 | class ProviderHelper 13 | { 14 | public static RegistryKey GetRegistryKey(ref string path) 15 | { 16 | RegistryKey root = null; 17 | path = path.ToUpperInvariant(); 18 | 19 | if (path.StartsWith("HKLM:")) 20 | { 21 | root = Registry.LocalMachine; 22 | path = path.Replace("HKLM:", string.Empty); 23 | } 24 | else if (path.StartsWith("HKCU:")) 25 | { 26 | root = Registry.CurrentUser; 27 | path = path.Replace("HKCU:", string.Empty); 28 | } 29 | else if (path.StartsWith("HKCR:")) 30 | { 31 | root = Registry.ClassesRoot; 32 | path = path.Replace("HKCR:", string.Empty); 33 | } 34 | else if (path.StartsWith("HKU:")) 35 | { 36 | root = Registry.Users; 37 | path = path.Replace("HKU:", string.Empty); 38 | } 39 | 40 | if (root != null && path.StartsWith(@"\")) 41 | path = path.Substring(1); 42 | 43 | return root; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/ReflectionHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using NoPowerShell.Commands; 5 | 6 | /* 7 | Author: @bitsadmin 8 | Website: https://github.com/bitsadmin 9 | License: BSD 3-Clause 10 | */ 11 | 12 | namespace NoPowerShell.HelperClasses 13 | { 14 | class ReflectionHelper 15 | { 16 | /// 17 | /// Using reflection determine available commands 18 | /// 19 | /// List of commands 20 | public static Dictionary GetCommands() 21 | { 22 | Dictionary commandTypes = new Dictionary(); 23 | foreach (Type t in Assembly.GetExecutingAssembly().GetTypes()) 24 | { 25 | if (t.BaseType == typeof(PSCommand)) 26 | { 27 | CaseInsensitiveList aliases = null; 28 | PropertyInfo aliasProperty = t.GetProperty("Aliases", BindingFlags.Static | BindingFlags.Public); 29 | if (aliasProperty != null) 30 | aliases = (CaseInsensitiveList)aliasProperty.GetValue(null, null); 31 | else 32 | aliases = new CaseInsensitiveList(); 33 | 34 | commandTypes.Add(t, aliases); 35 | } 36 | } 37 | 38 | return commandTypes; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/RegistryHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Win32; 2 | 3 | /* 4 | Author: @bitsadmin 5 | Website: https://github.com/bitsadmin 6 | License: BSD 3-Clause 7 | */ 8 | 9 | namespace NoPowerShell.HelperClasses 10 | { 11 | class RegistryHelper 12 | { 13 | public static RegistryKey GetRoot(ref string path) 14 | { 15 | RegistryKey root = null; 16 | 17 | path = path.ToUpperInvariant(); 18 | if (path.StartsWith("HKLM:")) 19 | { 20 | root = Registry.LocalMachine; 21 | path = path.Replace("HKLM:", string.Empty); 22 | } 23 | else if (path.StartsWith("HKCU:")) 24 | { 25 | root = Registry.CurrentUser; 26 | path = path.Replace("HKCU:", string.Empty); 27 | } 28 | else if (path.StartsWith("HKCR:")) 29 | { 30 | root = Registry.ClassesRoot; 31 | path = path.Replace("HKCR:", string.Empty); 32 | } 33 | else if (path.StartsWith("HKU:")) 34 | { 35 | root = Registry.Users; 36 | path = path.Replace("HKU:", string.Empty); 37 | } 38 | else 39 | throw new NoPowerShellException("Unknown registry path: \"{0}\"", path); 40 | 41 | if (path.StartsWith(@"\")) 42 | path = path.Substring(1); 43 | 44 | return root; 45 | } 46 | 47 | public static bool IsRegistryPath(string path) 48 | { 49 | string checkPath = path.ToUpperInvariant(); 50 | 51 | return checkPath.StartsWith("HKLM:") || checkPath.StartsWith("HKCU:") || checkPath.StartsWith("HKCR:") || checkPath.StartsWith("HKU:"); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/ResultPrinter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.HelperClasses 12 | { 13 | public class ResultPrinter 14 | { 15 | public static string OutputResults(CommandResult results) 16 | { 17 | if (results == null) 18 | return string.Empty; 19 | 20 | switch (results.Output) 21 | { 22 | case CommandResult.OutputType.List: 23 | return FormatList(results); 24 | case CommandResult.OutputType.Table: 25 | return FormatTable(results); 26 | default: 27 | return AutoFormat(results); 28 | } 29 | } 30 | 31 | public static string AutoFormat(CommandResult results) 32 | { 33 | // In case of raw data output without headings 34 | if (results.Count == 1 && results[0].ContainsKey(string.Empty)) 35 | return FormatRaw(results); 36 | // Only single row result 37 | else if (results.Count == 1) 38 | return FormatList(results); 39 | // List of results 40 | else 41 | return FormatTable(results); 42 | } 43 | 44 | private static string FormatRaw(CommandResult results) 45 | { 46 | return results[0][string.Empty]; 47 | } 48 | 49 | public static string FormatTable(CommandResult results) 50 | { 51 | StringBuilder sb = new StringBuilder(); 52 | 53 | // No results 54 | if (results.Count == 0) 55 | return string.Empty; 56 | 57 | Dictionary columns = CalcColumnWidths(results); 58 | 59 | // Print header 60 | int columnCount = columns.Count; 61 | int currentCol = 0; 62 | string separator = string.Empty; 63 | foreach (string column in columns.Keys) 64 | { 65 | currentCol++; 66 | 67 | string paddedSeparator = new string('-', column.Length) + new string(' ', columns[column] - column.Length + 1); 68 | string paddedValue = column.PadRight(columns[column]); 69 | 70 | // The most right column does not need to be padded 71 | if (columnCount == currentCol) 72 | { 73 | paddedSeparator = new string('-', column.Length); 74 | paddedValue = column; 75 | } 76 | separator += paddedSeparator; 77 | 78 | sb.AppendFormat("{0} ", paddedValue); 79 | } 80 | sb.AppendLine(); 81 | sb.AppendLine(separator); 82 | 83 | // Print data 84 | foreach (ResultRecord row in results) 85 | { 86 | currentCol = 0; 87 | foreach (string column in columns.Keys) 88 | { 89 | currentCol++; 90 | string value = null; 91 | if (row.ContainsKey(column.Trim())) 92 | value = row[column.Trim()]; 93 | 94 | if (value == null) 95 | value = string.Empty; 96 | 97 | // The most right column does not need to be padded 98 | string paddedValue = value.PadRight(columns[column] + 1); 99 | if (currentCol == columnCount) 100 | paddedValue = value; 101 | 102 | sb.Append(paddedValue); 103 | } 104 | sb.AppendLine(); 105 | } 106 | 107 | return sb.ToString(); 108 | } 109 | 110 | public static string FormatList(CommandResult results) 111 | { 112 | StringBuilder sb = new StringBuilder(); 113 | 114 | // No results 115 | if (results.Count == 0) 116 | return string.Empty; 117 | 118 | Dictionary columns = CalcColumnWidths(results); 119 | 120 | // Determine maximum column width 121 | int maxColumnLength = -1; 122 | foreach (string column in columns.Keys) 123 | { 124 | if (column.Length > maxColumnLength) 125 | maxColumnLength = column.Length; 126 | } 127 | 128 | // Print data 129 | foreach (ResultRecord result in results) 130 | { 131 | foreach (string column in columns.Keys) 132 | { 133 | sb.AppendFormat("{0} : {1}\r\n", column.PadRight(maxColumnLength), result[column]); 134 | } 135 | sb.AppendLine(); 136 | } 137 | 138 | return sb.ToString(); 139 | } 140 | 141 | private static Dictionary CalcColumnWidths(CommandResult results) 142 | { 143 | Dictionary columnWidths = new Dictionary(results[0].Keys.Count); 144 | 145 | foreach (string key in results[0].Keys) 146 | { 147 | columnWidths.Add(key, key.Length); 148 | } 149 | 150 | string[] columnNames = new string[columnWidths.Count]; 151 | columnWidths.Keys.CopyTo(columnNames, 0); 152 | 153 | // Iterate over results in output 154 | foreach (ResultRecord result in results) 155 | { 156 | // Iterate over columns of reach result 157 | foreach (string key in columnNames) 158 | { 159 | if (!result.ContainsKey(key)) 160 | continue; 161 | 162 | string value = result[key]; 163 | if (value == null) 164 | continue; 165 | 166 | if (value.Length > columnWidths[key]) 167 | columnWidths[key] = value.Length; 168 | } 169 | } 170 | 171 | return columnWidths; 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/ResultRecord.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.HelperClasses 12 | { 13 | public class ResultRecord : Dictionary, ICloneable 14 | { 15 | public ResultRecord() : base(StringComparer.OrdinalIgnoreCase) 16 | { 17 | } 18 | 19 | public ResultRecord(int capacity) : base(capacity, StringComparer.InvariantCultureIgnoreCase) 20 | { 21 | } 22 | 23 | public ResultRecord(Dictionary dictionary) : base(dictionary, StringComparer.InvariantCultureIgnoreCase) 24 | { 25 | } 26 | 27 | public object Clone() 28 | { 29 | return new ResultRecord(this); 30 | } 31 | 32 | public override bool Equals(object obj) 33 | { 34 | // If parameter is null or an incorrect type, it for sure isn't equal 35 | if (!(obj is Dictionary dict2)) 36 | return false; 37 | 38 | // If count of columns is different, it isn't equal 39 | if (this.Count != dict2.Count) 40 | return false; 41 | 42 | // Validate values in all attributes 43 | foreach (KeyValuePair kv1 in this) 44 | { 45 | // If attribute does not exist in second object 46 | if (!dict2.ContainsKey(kv1.Key)) 47 | return false; 48 | 49 | // If attribute value does not match the value in the second object 50 | if (dict2[kv1.Key] != kv1.Value) 51 | return false; 52 | } 53 | 54 | return true; 55 | } 56 | 57 | public override int GetHashCode() 58 | { 59 | return base.GetHashCode(); 60 | } 61 | 62 | public override string ToString() 63 | { 64 | string[] values = new string[this.Count]; 65 | int i = 0; 66 | 67 | // Concatenate values with a vertical bar (|) 68 | foreach(KeyValuePair kvp in this) 69 | { 70 | values[i] = kvp.Value; 71 | i++; 72 | } 73 | 74 | return string.Join(" | ", values); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Source/NoPowerShell/HelperClasses/WmiHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Management; 4 | 5 | /* 6 | Author: @bitsadmin 7 | Website: https://github.com/bitsadmin 8 | License: BSD 3-Clause 9 | */ 10 | 11 | namespace NoPowerShell.HelperClasses 12 | { 13 | class WmiHelper 14 | { 15 | public static CommandResult ExecuteWmiQuery(string wmiQuery, string computerName, string username, string password) 16 | { 17 | return ExecuteWmiQuery(@"ROOT\CIMV2", wmiQuery, computerName, username, password); 18 | } 19 | 20 | public static CommandResult ExecuteWmiQuery(string wmiNamespace, string wmiQuery, string computerName, string username, string password) 21 | { 22 | CommandResult queryResults = null; 23 | 24 | computerName = computerName ?? "."; 25 | ManagementScope scope = GetScope(wmiNamespace, computerName, username, password); 26 | 27 | ObjectQuery query = new ObjectQuery(wmiQuery); 28 | ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); 29 | 30 | ManagementObjectCollection queryCollection = searcher.Get(); 31 | Dictionary columns = new Dictionary(StringComparer.InvariantCultureIgnoreCase); 32 | queryResults = new CommandResult(queryCollection.Count); 33 | 34 | // Determine column order of SELECT query 35 | string lowerWmiQuery = wmiQuery.ToLowerInvariant(); 36 | bool wildCardSelect = false; 37 | if (lowerWmiQuery.StartsWith("select ")) 38 | { 39 | int start = wmiQuery.ToLower().IndexOf("select") + "select".Length; 40 | int length = wmiQuery.ToLower().IndexOf(" from") - start; 41 | string columns_string = wmiQuery.Substring(start, length); 42 | string[] dirty_columns = columns_string.Split(','); 43 | foreach (string col in dirty_columns) 44 | columns.Add(col.Trim(), col.Trim().Length); 45 | 46 | // Case of SELECT * 47 | if (columns.ContainsKey("*")) 48 | { 49 | columns = new Dictionary(StringComparer.InvariantCultureIgnoreCase); 50 | wildCardSelect = true; 51 | } 52 | } 53 | // Other types of queries 54 | else if (lowerWmiQuery.StartsWith("associators of ") || lowerWmiQuery.StartsWith("references of")) 55 | { 56 | columns = new Dictionary(StringComparer.InvariantCultureIgnoreCase); 57 | wildCardSelect = true; 58 | } 59 | else 60 | throw new NoPowerShellException(string.Format("Unknown type of WMI query: {0}", wmiQuery)); 61 | 62 | // Collect data 63 | foreach (ManagementObject m in queryCollection) 64 | { 65 | ResultRecord result = new ResultRecord(m.Properties.Count); 66 | 67 | // Case of SELECT * 68 | if (wildCardSelect) 69 | { 70 | foreach (PropertyData data in m.Properties) 71 | { 72 | columns.Add(data.Name, data.Name.Length); 73 | } 74 | wildCardSelect = false; 75 | } 76 | 77 | // Prepare order of columns 78 | foreach (string column in columns.Keys) 79 | result.Add(column, null); 80 | 81 | // Collect attributes 82 | foreach (PropertyData data in m.Properties) 83 | { 84 | string key = data.Name; 85 | string value = string.Empty; 86 | if (data.Value != null) 87 | { 88 | if (data.Value.GetType() == typeof(string[])) 89 | value = string.Join(", ", (string[])data.Value); 90 | else 91 | value = Convert.ToString(data.Value); 92 | } 93 | 94 | result[key] = value; 95 | } 96 | 97 | queryResults.Add(result); 98 | } 99 | 100 | return queryResults; 101 | } 102 | 103 | public static CommandResult InvokeWmiMethod(string wmiNamespace, string wmiClass, string methodName, string methodArguments, string computerName, string username, string password) 104 | { 105 | CommandResult invokeResults = new CommandResult(1); 106 | 107 | ManagementScope scope = GetScope(wmiNamespace, computerName, username, password); 108 | ManagementClass mgmtClass = new ManagementClass(scope.Path.Path, wmiClass, null); 109 | MethodData method = mgmtClass.Methods[methodName]; 110 | 111 | // -1 because ReturnValue does not count 112 | int paramCount = method.InParameters.Properties.Count + method.OutParameters.Properties.Count - 1; 113 | 114 | // Invoke the method 115 | object[] methodArgs = new object[paramCount]; 116 | methodArgs[0] = methodArguments; // TODO, it should be possible to provide more arguments 117 | object returnValue = mgmtClass.InvokeMethod(methodName, methodArgs); 118 | 119 | // Store the ReturnValue 120 | ResultRecord outParams = new ResultRecord(); 121 | outParams.Add("ReturnValue", Convert.ToString(returnValue)); 122 | 123 | // Store other outParams 124 | int i = method.InParameters.Properties.Count; 125 | foreach (PropertyData param in method.OutParameters.Properties) 126 | { 127 | // ReturnValue is not stored in the methodarguments, 128 | // but instead is just the return value of the InvokeMethod method 129 | if (param.Name == "ReturnValue") 130 | continue; 131 | 132 | outParams.Add(param.Name, Convert.ToString(methodArgs[i])); 133 | i++; 134 | } 135 | 136 | invokeResults.Add(outParams); 137 | 138 | return invokeResults; 139 | } 140 | 141 | private static ManagementScope GetScope(string wmiNamespace, string computerName, string username, string password) 142 | { 143 | // User credentials cannot be used for local connections 144 | if (computerName == ".") 145 | username = password = null; 146 | 147 | ConnectionOptions options = new ConnectionOptions() 148 | { 149 | Impersonation = ImpersonationLevel.Impersonate, 150 | Username = username, 151 | Password = password 152 | }; 153 | ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\{1}", computerName, wmiNamespace), options); 154 | scope.Connect(); 155 | 156 | return scope; 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using NoPowerShell.Commands; 4 | using NoPowerShell.Commands.Core; 5 | using NoPowerShell.Commands.Utility; 6 | using NoPowerShell.HelperClasses; 7 | #if BOFBUILD 8 | using BOFNET; 9 | #endif 10 | 11 | /* 12 | Author: @bitsadmin 13 | Website: https://github.com/bitsadmin 14 | License: BSD 3-Clause 15 | */ 16 | 17 | namespace NoPowerShell 18 | { 19 | #if BOFBUILD 20 | public class Program : BeaconObject 21 | { 22 | public Program(BeaconApi api) : base(api) { } 23 | 24 | public override void Go(string[] args) 25 | { 26 | #else 27 | partial class Program 28 | { 29 | [STAThread] // Required for the *-Clipboard cmdlets 30 | public static void Main(string[] args) 31 | { 32 | #endif 33 | // Using reflection determine available commands 34 | Dictionary availableCommands = ReflectionHelper.GetCommands(); 35 | List userCommands = null; 36 | 37 | // If no arguments are provided to the executable, show help 38 | if (args.Length == 0) 39 | { 40 | Console.WriteLine("== NoPowerShell v{0} ==\r\nWebsite: {1}\r\n{2}", VERSION, WEBSITE, USAGE); 41 | userCommands = new List(1) { new GetCommandCommand(null) }; 42 | } 43 | // Parse pipes in commandline arguments and commands within pipes 44 | else 45 | { 46 | string error = null; 47 | 48 | try 49 | { 50 | userCommands = PipeParser.ParseArguments(args, availableCommands); 51 | } 52 | catch (ParameterBindingException ex) 53 | { 54 | error = ex.Message; 55 | } 56 | catch (CommandNotFoundException ex) 57 | { 58 | error = string.Join("", new string[] { ex.Message, HELP }); 59 | } 60 | 61 | if (error != null) 62 | { 63 | #if BOFBUILD 64 | BeaconConsole.WriteLine(error); 65 | #else 66 | WriteError(error); 67 | return; 68 | #endif 69 | } 70 | } 71 | 72 | // Add output to console if no explicit output is provided 73 | Type lastCommand = userCommands[userCommands.Count - 1].GetType(); 74 | bool justOutput = false; 75 | if (lastCommand != typeof(FormatListCommand) && lastCommand != typeof(FormatTableCommand)) 76 | justOutput = true; 77 | 78 | CommandResult result = null; 79 | #if DEBUG 80 | // Execute commands in pipeline 81 | foreach (PSCommand command in userCommands) 82 | { 83 | result = command.Execute(result); 84 | } 85 | #else 86 | PSCommand mostRecentCommand = null; 87 | try 88 | { 89 | // Execute commands in pipeline 90 | foreach (PSCommand command in userCommands) 91 | { 92 | mostRecentCommand = command; 93 | result = command.Execute(result); 94 | } 95 | } 96 | catch (NoPowerShellException e) 97 | { 98 | WriteError(string.Format("{0} : {1}", mostRecentCommand.ToString(), e.Message)); 99 | return; 100 | } 101 | catch (Exception e) 102 | { 103 | WriteError(string.Format("{0} : {1}", mostRecentCommand.ToString(), e.ToString())); 104 | return; 105 | } 106 | #endif 107 | 108 | // Output to screen 109 | if (justOutput) 110 | { 111 | string output = ResultPrinter.OutputResults(result); 112 | 113 | #if BOFBUILD 114 | BeaconConsole.WriteLine(output); 115 | #else 116 | Console.Write(output); 117 | #endif 118 | } 119 | } 120 | 121 | public static void WriteError(string error, params object[] args) 122 | { 123 | // Save existing color 124 | ConsoleColor BackgroundColor = Console.BackgroundColor; 125 | ConsoleColor ForegroundColor = Console.ForegroundColor; 126 | 127 | // Change color to error text 128 | Console.BackgroundColor = ConsoleColor.Black; 129 | Console.ForegroundColor = ConsoleColor.Red; 130 | 131 | Console.WriteLine(error, args); 132 | 133 | // Revert colors 134 | Console.BackgroundColor = BackgroundColor; 135 | Console.ForegroundColor = ForegroundColor; 136 | } 137 | 138 | public static void WriteWarning(string warning, params object[] args) 139 | { 140 | // Save existing color 141 | ConsoleColor BackgroundColor = Console.BackgroundColor; 142 | ConsoleColor ForegroundColor = Console.ForegroundColor; 143 | 144 | // Change color to error text 145 | Console.BackgroundColor = ConsoleColor.Black; 146 | Console.ForegroundColor = ConsoleColor.DarkYellow; 147 | 148 | Console.WriteLine(warning, args); 149 | 150 | // Revert colors 151 | Console.BackgroundColor = BackgroundColor; 152 | Console.ForegroundColor = ForegroundColor; 153 | } 154 | 155 | public static readonly string VERSION = "1.25"; 156 | public static readonly string WEBSITE = "https://github.com/bitsadmin/nopowershell"; 157 | #if !DLLBUILD 158 | private static readonly string USAGE = "Usage: NoPowerShell.exe [Command] [Parameters] | [Command2] [Parameters2] etc.\r\n"; 159 | private static readonly string HELP = "\r\nExecute NoPowerShell without parameters to list all available cmdlets."; 160 | #else 161 | private static readonly string USAGE = ""; 162 | private static readonly string HELP = " Type 'help' to list all available cmdlets."; 163 | #endif 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /Source/NoPowerShell/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("NoPowerShell")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Bitsadmin")] 12 | [assembly: AssemblyProduct("NoPowerShell")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("555ad0ac-1fdb-4016-8257-170a74cb2f55")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Source/NoPowerShell/lib/BOF.NET/net35/BOFNET.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Source/NoPowerShell/lib/BOF.NET/net35/BOFNET.dll -------------------------------------------------------------------------------- /Source/NoPowerShell/lib/BOF.NET/net35/bofnet_execute.cpp.x64.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Source/NoPowerShell/lib/BOF.NET/net35/bofnet_execute.cpp.x64.obj -------------------------------------------------------------------------------- /Source/NoPowerShell/lib/BOF.NET/net35/bofnet_execute.cpp.x86.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Source/NoPowerShell/lib/BOF.NET/net35/bofnet_execute.cpp.x86.obj -------------------------------------------------------------------------------- /Source/NoPowerShell/lib/BOF.NET/net40/BOFNET.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Source/NoPowerShell/lib/BOF.NET/net40/BOFNET.dll -------------------------------------------------------------------------------- /Source/NoPowerShell/lib/BOF.NET/net40/bofnet_execute.cpp.x64.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Source/NoPowerShell/lib/BOF.NET/net40/bofnet_execute.cpp.x64.obj -------------------------------------------------------------------------------- /Source/NoPowerShell/lib/BOF.NET/net40/bofnet_execute.cpp.x86.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitsadmin/nopowershell/bf1466d8eda5a1dd58864bc7a6ea98dba650ff85/Source/NoPowerShell/lib/BOF.NET/net40/bofnet_execute.cpp.x86.obj -------------------------------------------------------------------------------- /Source/NoPowerShell/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | --------------------------------------------------------------------------------