Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file modified lib/PowerShell/System.Management.Automation.dll
Binary file not shown.
2 changes: 2 additions & 0 deletions src/Chocolatey.PowerShell/Chocolatey.PowerShell.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,15 @@
</Compile>
<Compile Include="Commands\GetEnvironmentVariableCommand.cs" />
<Compile Include="Commands\GetEnvironmentVariableNamesCommand.cs" />
<Compile Include="Commands\GetPackageScriptParametersCommand.cs" />
<Compile Include="Commands\InstallChocolateyPathCommand.cs" />
<Compile Include="Commands\SetEnvironmentVariableCommand.cs" />
<Compile Include="Commands\TestProcessAdminRightsCommand.cs" />
<Compile Include="Commands\UninstallChocolateyPathCommand.cs" />
<Compile Include="Commands\UpdateSessionEnvironmentCommand.cs" />
<Compile Include="Helpers\Elevation.cs" />
<Compile Include="Helpers\EnvironmentHelper.cs" />
<Compile Include="Helpers\PackageParameter.cs" />
<Compile Include="Helpers\Paths.cs" />
<Compile Include="Helpers\ProcessInformation.cs" />
<Compile Include="Helpers\PSHelper.cs" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright © 2017 - 2025 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using Chocolatey.PowerShell.Helpers;
using Chocolatey.PowerShell.Shared;

namespace Chocolatey.PowerShell.Commands
{
/// <summary>
/// Parses a script and returns a hash table of parameters that are present in the package params, along with their values.
/// </summary>
/// <param name="ScriptPath">A path to a script to parse parameters from.</param>
/// <param name="Parameters">A string containing parameters to be parsed.</param>
/// <returns>A hashtable of parameters present in <paramref name="ScriptPath"> and also in <paramref name="Parameters"> (or the envvar).</returns>
[Cmdlet(VerbsCommon.Get, "PackageScriptParameters")]
[OutputType(typeof(Hashtable))]
public class GetScriptParametersCommand : ChocolateyCmdlet
{
[Parameter(Mandatory = true, Position = 0)]
public string ScriptPath { get; set; }

[Parameter(Mandatory = false, Position = 1)]
public string Parameters { get; set; } = string.Empty;

protected override void End()
{
var packageParameters = PackageParameter.GetParameters(this, Parameters);
WriteObject(GetPackageParameterHashtable(ScriptPath, packageParameters));
}

private Hashtable GetPackageParameterHashtable(string scriptPath, Hashtable packageParameters)
{

var splatHash = new Hashtable(StringComparer.OrdinalIgnoreCase);

// Check what parameters the script has
var scriptParameters = GetScriptParameters(scriptPath);

// For each of those in PackageParameters, add it to the splat
foreach (var parameter in scriptParameters)
{
if (packageParameters.ContainsKey(parameter))
{
splatHash.Add(parameter, packageParameters[parameter]);
}
}

return splatHash;
}

private List<string> GetScriptParameters(string scriptPath)
{
Token[] tokensRef = null;
ParseError[] errorsRef = null;
var parsedAst = Parser.ParseFile(scriptPath, out tokensRef, out errorsRef);
var scriptParameters = parsedAst.ParamBlock != null ? parsedAst.ParamBlock.Parameters.Select(p => p.Name.VariablePath.UserPath.ToString()).ToList() : new List<string>();
WriteVerbose($"Found {scriptParameters.Count()} parameter(s) in '{scriptPath}'");

return scriptParameters;
}
}
}
94 changes: 94 additions & 0 deletions src/Chocolatey.PowerShell/Helpers/PackageParameter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright © 2017 - 2025 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using System.Text.RegularExpressions;

namespace Chocolatey.PowerShell.Helpers
{
public static class PackageParameter
{
private const string PackageParameterPattern = @"(?:^|\s+)\/(?<ItemKey>[^\:\=\s)]+)(?:(?:\:|=){1}(?:\'|\""){0,1}(?<ItemValue>.*?)(?:\'|\""){0,1}(?:(?=\s+\/)|$))?";
private static readonly Regex _packageParameterRegex = new Regex(PackageParameterPattern, RegexOptions.Compiled);

public static Hashtable GetParameters(PSCmdlet cmdlet, string parameters)
{
var paramHash = new Hashtable(StringComparer.OrdinalIgnoreCase);

if (!string.IsNullOrEmpty(parameters))
{
paramHash = AddParameters(cmdlet, parameters, paramHash);
}
else
{
var packageParameters = EnvironmentHelper.GetVariable(
cmdlet,
"ChocolateyPackageParameters",
EnvironmentVariableTarget.Process);
if (!string.IsNullOrEmpty(packageParameters))
{
paramHash = AddParameters(cmdlet, packageParameters, paramHash);
}

var sensitivePackageParameters = EnvironmentHelper.GetVariable(
cmdlet,
"ChocolateyPackageParametersSensitive",
EnvironmentVariableTarget.Process);
if (!string.IsNullOrEmpty(sensitivePackageParameters))
{
paramHash = AddParameters(cmdlet, sensitivePackageParameters, paramHash, logParams: false);
}
}

return paramHash;
}

private static Hashtable AddParameters(PSCmdlet cmdlet, string paramString, Hashtable paramHash, bool logParams = true)
{;
foreach (Match match in _packageParameterRegex.Matches(paramString))
{
var name = match.Groups["ItemKey"].Value.Trim();
var valueGroup = match.Groups["ItemValue"];

object value;
if (valueGroup.Success)
{
value = valueGroup.Value.Trim();
}
else
{
value = (object)true;
}

if (logParams)
{
cmdlet.WriteDebug($"Adding package param '{name}'='{value}'");
}
else
{
cmdlet.WriteDebug($"Adding package param '{name}' (value not logged)");
}

paramHash[name] = value;
}

return paramHash;
}
}
}
10 changes: 5 additions & 5 deletions src/chocolatey.resources/chocolatey.resources.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -260,11 +260,11 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="helpers\functions\Get-PackageParameters.ps1">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="helpers\functions\Get-PackageParameters.ps1">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
Expand Down
4 changes: 3 additions & 1 deletion src/chocolatey.resources/helpers/chocolateyScriptRunner.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ if ($preRunHookScripts) {
}

if ($packageScript) {
Write-Debug "Finding Parameters for package script '$packageScript'";
$scriptParameters = Get-PackageScriptParameters -PackageParameters $packageParameters -Script $packageScript
Write-Debug "Running package script '$packageScript'";
& "$packageScript"
& "$packageScript" @scriptParameters
}
$scriptSuccess = $?
$lastExecutableExitCode = $LASTEXITCODE
Expand Down
Loading