Skip to content

Commit

Permalink
temp commit
Browse files Browse the repository at this point in the history
  • Loading branch information
vexx32 committed Feb 20, 2024
1 parent 48ee5cf commit be84062
Show file tree
Hide file tree
Showing 55 changed files with 6,576 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Chocolatey.PowerShell/Chocolatey.PowerShell.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>9.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<None Remove="StringResources\EnvironmentVariables.cs~RF1e9b1f0.TMP" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.Management.Automation">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\PowerShell\System.Management.Automation.dll</HintPath>
</Reference>
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0"></PackageReference>
</ItemGroup>

</Project>
238 changes: 238 additions & 0 deletions src/Chocolatey.PowerShell/ChocolateyCmdlet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
// Copyright © 2017-2019 Chocolatey Software, Inc ("Chocolatey")
// Copyright © 2015-2017 RealDimensions Software, LLC
//
// Chocolatey Professional, Chocolatey for Business, and Chocolatey Architect are licensed software.
//
// =====================================================================
// End-User License Agreement
// Chocolatey Professional, Chocolatey for Service Providers, Chocolatey for Business,
// and/or Chocolatey Architect
// =====================================================================
//
// IMPORTANT- READ CAREFULLY: This Chocolatey Software ("Chocolatey") End-User License Agreement
// ("EULA") is a legal agreement between you ("END USER") and Chocolatey for all Chocolatey products,
// controls, source code, demos, intermediate files, media, printed materials, and "online" or electronic
// documentation (collectively "SOFTWARE PRODUCT(S)") contained with this distribution.
//
// Chocolatey grants to you as an individual or entity, a personal, nonexclusive license to install and use the
// SOFTWARE PRODUCT(S). By installing, copying, or otherwise using the SOFTWARE PRODUCT(S), you
// agree to be bound by the terms of this EULA. If you do not agree to any part of the terms of this EULA, DO
// NOT INSTALL, USE, OR EVALUATE, ANY PART, FILE OR PORTION OF THE SOFTWARE PRODUCT(S).
//
// In no event shall Chocolatey be liable to END USER for damages, including any direct, indirect, special,
// incidental, or consequential damages of any character arising as a result of the use or inability to use the
// SOFTWARE PRODUCT(S) (including but not limited to damages for loss of goodwill, work stoppage, computer
// failure or malfunction, or any and all other commercial damages or losses).
//
// The liability of Chocolatey to END USER for any reason and upon any cause of action related to the
// performance of the work under this agreement whether in tort or in contract or otherwise shall be limited to the
// amount paid by the END USER to Chocolatey pursuant to this agreement.
//
// ALL SOFTWARE PRODUCT(S) are licensed not sold. If you are an individual, you must acquire an individual
// license for the SOFTWARE PRODUCT(S) from Chocolatey or its authorized resellers. If you are an entity, you
// must acquire an individual license for each machine running the SOFTWARE PRODUCT(S) within your
// organization from Chocolatey or its authorized resellers. Both virtual and physical machines running the
// SOFTWARE PRODUCT(S) or benefitting from licensed features such as Package Builder or Package
// Internalizer must be counted in the SOFTWARE PRODUCT(S) licenses quantity of the organization.

namespace Chocolatey.PowerShell
{
using Chocolatey.PowerShell.Helpers;
using Chocolatey.PowerShell.StringResources;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;

public abstract class ChocolateyCmdlet : PSCmdlet
{
private readonly object _lock = new object();
private readonly CancellationTokenSource _pipelineStopTokenSource = new CancellationTokenSource();

protected CancellationToken PipelineStopToken => _pipelineStopTokenSource.Token;

protected Dictionary<string, object> BoundParameters => MyInvocation.BoundParameters;

protected string ErrorId => GetType().Name + "Error";

protected string ChocolateyInstallLocation => PowerShellHelper.GetInstallLocation(this);

protected bool Debug => MyInvocation.BoundParameters.ContainsKey("Debug")
? ConvertTo<SwitchParameter>(MyInvocation.BoundParameters["Debug"]).ToBool()
: ConvertTo<ActionPreference>(GetVariableValue(PreferenceVariables.Debug)) != ActionPreference.SilentlyContinue;

protected override void BeginProcessing()
{
WriteCmdletCallDebugMessage();
}

protected override void EndProcessing()
{
WriteCmdletCompletionDebugMessage();
}

protected override void StopProcessing()
{
lock (_lock)
{
_pipelineStopTokenSource.Cancel();
}
}

protected void WriteCmdletCallDebugMessage()
{
var logMessage = new StringBuilder()
.Append("Running ")
.Append(MyInvocation.InvocationName);

foreach (var param in MyInvocation.BoundParameters)
{
if (param.Key == "ignoredArguments")
{
continue;
}

var paramValue = IsEqual(param.Key, "SensitiveStatements") || IsEqual(param.Key, "Password")
? "[REDACTED]"
: param.Value is IList list
? string.Join(" ", list)
: LanguagePrimitives.ConvertTo(param.Value, typeof(string));

logMessage.Append($" -{param.Key} '{paramValue}'");
}

WriteDebug(logMessage.ToString());
}

protected void WriteCmdletCompletionDebugMessage()
{
WriteDebug($"Finishing '{MyInvocation.InvocationName}'");
}

protected string EnvironmentVariable(string name)
=> EnvironmentHelper.GetVariable(name);

protected string EnvironmentVariable(string name, EnvironmentVariableTarget scope)
=> EnvironmentVariable(name, scope, preserveVariables: false);

protected string EnvironmentVariable(string name, EnvironmentVariableTarget scope, bool preserveVariables)
=> EnvironmentHelper.GetVariable(this, name, scope, preserveVariables);

protected void SetEnvironmentVariable(string variable, string value)
=> EnvironmentHelper.SetVariable(variable, value);

protected void SetEnvironmentVariable(string name, string value, EnvironmentVariableTarget scope)
=> EnvironmentHelper.SetVariable(name, value, scope);

protected Collection<PSObject> GetChildItem(string[] path, bool recurse, bool force, bool literalPath)
=> PowerShellHelper.GetChildItem(this, path, recurse, force, literalPath);

protected Collection<PSObject> GetChildItem(string path, bool recurse)
=> PowerShellHelper.GetChildItem(this, path, recurse);

protected Collection<PSObject> GetChildItem(string path)
=> PowerShellHelper.GetChildItem(this, path);

internal Collection<PSObject> GetItem(string path, bool force, bool literalPath)
=> PowerShellHelper.GetItem(this, path, force, literalPath);

internal Collection<PSObject> GetItem(string path)
=> PowerShellHelper.GetItem(this, path);

internal Collection<PSObject> GetItem(string path, bool literalPath)
=> PowerShellHelper.GetItem(this, path, literalPath);

protected bool IsEqual(object first, object second)
=> PowerShellHelper.IsEqual(first, second);

protected void WriteHost(string message)
=> PowerShellHelper.WriteHost(this, message);

protected new void WriteDebug(string message)
=> PowerShellHelper.WriteDebug(this, message);

protected new void WriteVerbose(string message)
=> PowerShellHelper.WriteVerbose(this, message);

protected new void WriteWarning(string message)
=> PowerShellHelper.WriteWarning(this, message);

protected string CombinePaths(string parent, params string[] childPaths)
=> PowerShellHelper.CombinePaths(this, parent, childPaths);

protected void EnsureDirectoryExists(string directory)
=> PowerShellHelper.EnsureDirectoryExists(this, directory);

protected string GetParentDirectory(string path)
=> PowerShellHelper.GetParentDirectory(this, path);

protected static string GetFileName(string path)
=> PowerShellHelper.GetFileName(path);

protected string GetUnresolvedPath(string path)
=> PowerShellHelper.GetUnresolvedPath(this, path);

protected string? GetCurrentDirectory()
=> PowerShellHelper.GetCurrentDirectory(this);

protected FileInfo? GetFileInfoFor(string path)
=> PowerShellHelper.GetFileInfoFor(this, path);

protected string GetFullPath(string path)
=> PowerShellHelper.GetFullPath(this, path);

protected bool ItemExists(string path)
=> PowerShellHelper.ItemExists(this, path);

protected bool ContainerExists(string path)
=> PowerShellHelper.ContainerExists(this, path);

protected void CopyFile(string source, string destination, bool overwriteExisting)
=> PowerShellHelper.CopyFile(this, source, destination, overwriteExisting);

protected void DeleteFile(string path)
=> PowerShellHelper.DeleteFile(this, path);

protected Collection<PSObject> NewDirectory(string path)
=> PowerShellHelper.NewDirectory(this, path);

protected Collection<PSObject> NewFile(string path)
=> PowerShellHelper.NewFile(this, path);

protected Collection<PSObject> NewItem(string path, string itemType)
=> PowerShellHelper.NewItem(this, path, itemType);

protected Collection<PSObject> NewItem(string path, string name, string itemType)
=> PowerShellHelper.NewItem(this, path, name, itemType);

protected void SetExitCode(int exitCode)
=> PowerShellHelper.SetExitCode(this, exitCode);

protected T ConvertTo<T>(object? value)
=> PowerShellHelper.ConvertTo<T>(value);

protected string Replace(string input, string pattern, string replacement)
=> PowerShellHelper.Replace(input, pattern, replacement);

protected string Replace(string input, string pattern, string replacement, bool caseSensitive)
=> PowerShellHelper.Replace(input, pattern, replacement, caseSensitive);

public void RemoveItem(string path)
=> PowerShellHelper.RemoveItem(this, path);

public void RemoveItem(string path, bool recurse)
=> PowerShellHelper.RemoveItem(this, path, recurse);

public void RemoveItem(string[] path, bool recurse, bool force, bool literalPath)
=> PowerShellHelper.RemoveItem(this, path, recurse, force, literalPath);


protected new void WriteObject(object value)
=> PowerShellHelper.WriteObject(this, value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
namespace Chocolatey.PowerShell.Commands
{
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Text;

[Cmdlet(VerbsCommon.Add, "ChocolateyPinnedTaskbarItem")]
public class AddChocolateyPinnedTaskbarItemCommand : ChocolateyCmdlet
{
/*
.SYNOPSIS
Creates an item in the task bar linking to the provided path.
.NOTES
Does not work with SYSTEM, but does not error. It warns with the error
message.
.INPUTS
None
.OUTPUTS
None
.PARAMETER TargetFilePath
The path to the application that should be launched when clicking on the
task bar icon.
.PARAMETER IgnoredArguments
Allows splatting with arguments that do not apply. Do not use directly.
.EXAMPLE
>
# This will create a Visual Studio task bar icon.
Install-ChocolateyPinnedTaskBarItem -TargetFilePath "${env:ProgramFiles(x86)}\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe"
.LINK
Install-ChocolateyShortcut
.LINK
Install-ChocolateyExplorerMenuItem
*/

[Parameter(Mandatory = true, Position = 0)]
[Alias("TargetFilePath")]
public string Path { get; set; } = string.Empty;

[Parameter(ValueFromRemainingArguments = true)]
public object[]? IgnoredArguments { get; set; }

protected override void EndProcessing()
{
const string verb = "Pin To Taskbar";
var targetFolder = GetParentDirectory(Path);
var targetItem = GetFileName(Path);

try
{
if (!ItemExists(Path))
{
WriteWarning($"'{Path}' does not exist, not able to pin to task bar");
return;
}

dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
var folder = shell.NameSpace(targetFolder);
var item = folder.ParseName(targetItem);

bool verbFound = false;
foreach (var itemVerb in item.Verbs())
{
var name = (string)itemVerb.Name;
if (name.Replace("&", string.Empty) == verb)
{
verbFound = true;
itemVerb.DoIt();
break;
}
}

if (!verbFound)
{
WriteHost($"TaskBar verb not found for {targetItem}. It may have already been pinned");
}

WriteHost($"'{Path}' has been pinned to the task bar on your desktop");
}
catch (Exception ex)
{
WriteWarning($"Unable to create pin. Error captured was {ex.Message}.");
}

base.EndProcessing();
}
}
}
Loading

0 comments on commit be84062

Please sign in to comment.