Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand Environment Variables. #128

Merged
merged 1 commit into from
Feb 11, 2025
Merged
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
34 changes: 12 additions & 22 deletions PowerShellToolsPro.Packager/Config/ConfigDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public PsPackConfig Deserialize(Hashtable configTable)
var config = new PsPackConfig();
config.Root = ReadScalarValue<string>(configTable, "Root");
config.Root = _pathResolver.Resolve(config.Root);

config.OutputPath = ReadScalarValue<string>(configTable, "OutputPath");
config.OutputPath = _pathResolver.Resolve(config.OutputPath);

Expand Down Expand Up @@ -81,7 +82,7 @@ public PsPackConfig Deserialize(string file)
Hashtable configTable;
using (var ps = PowerShell.Create())
{
ps.AddScript(contents);
ps.AddCommand("Import-PowerShellDataFile").AddParameter("Path", file);
configTable = ps.Invoke<Hashtable>().FirstOrDefault();

if (ps.HadErrors)
Expand All @@ -108,35 +109,24 @@ public PsPackConfig Deserialize(string file)
return (T)pSObject.BaseObject;
}

return (T)value;
}
catch (Exception ex)
{
throw new Exception($"Failed to read '{key}'. Expected '{typeof(T)}' but was '{table[key].GetType()}'.", ex);
}

}

private static T ReadScalarValue<T>(PSObject table, string key, T defaultValue = default(T))
{
try
{
if (!table.Properties.Any(x => x.Name.Equals(key, StringComparison.OrdinalIgnoreCase)))
if (typeof(T) == typeof(string))
{
return defaultValue;
}
var stringValue = value as string;
if (stringValue == null)
{
return defaultValue;
}

var value = table.Properties[key].Value;
if (value is PSObject pSObject)
{
return (T)pSObject.BaseObject;
value = Environment.ExpandEnvironmentVariables(stringValue);

return (T)value;
}

return (T)value;
}
catch (Exception ex)
{
throw new Exception($"Failed to read '{key}'. Expected '{typeof(T)}' but was '{table.Properties[key].GetType()}'.", ex);
throw new Exception($"Failed to read '{key}'. Expected '{typeof(T)}' but was '{table[key].GetType()}'.", ex);
}

}
Expand Down
Loading