Skip to content

Commit e3b59e0

Browse files
Staffan Gustafssonlzybkr
authored andcommitted
Moving Import-PowerShellDatafile from script to cmdlet (PowerShell#2750)
1 parent c74b2a7 commit e3b59e0

7 files changed

Lines changed: 111 additions & 67 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
using System;
2+
using System.Diagnostics.CodeAnalysis;
3+
using System.Management.Automation;
4+
using System.Management.Automation.Language;
5+
6+
namespace Microsoft.PowerShell.Commands
7+
{
8+
/// <summary>
9+
/// This class implements Import-PowerShellDataFile command.
10+
/// </summary>
11+
[Cmdlet(VerbsData.Import, "PowerShellDataFile", DefaultParameterSetName = "ByPath",
12+
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=623621", RemotingCapability = RemotingCapability.None)]
13+
public class ImportPowerShellDataFileCommand : PSCmdlet
14+
{
15+
bool _isLiteralPath;
16+
17+
/// <summary>
18+
/// Path specified, using globbing to resolve
19+
/// </summary>
20+
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")]
21+
[ValidateNotNullOrEmpty]
22+
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
23+
public string[] Path { get; set; }
24+
25+
/// <summary>
26+
/// Specifies a path to one or more locations, without globbing
27+
/// </summary>
28+
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByLiteralPath", ValueFromPipelineByPropertyName = true)]
29+
[ValidateNotNullOrEmpty]
30+
[Alias("PSPath")]
31+
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
32+
public string[] LiteralPath
33+
{
34+
get { return _isLiteralPath ? Path : null; }
35+
set { _isLiteralPath = true; Path = value; }
36+
}
37+
38+
/// <summary>
39+
/// For each path, resolve it, parse it and write all hashtables
40+
/// to the output stream
41+
/// </summary>
42+
protected override void ProcessRecord()
43+
{
44+
foreach (var path in Path)
45+
{
46+
var resolved = PathUtils.ResolveFilePath(path, this, _isLiteralPath);
47+
if(!string.IsNullOrEmpty(resolved) && System.IO.File.Exists(resolved))
48+
{
49+
Token[] tokens;
50+
ParseError[] errors;
51+
var ast = Parser.ParseFile(resolved, out tokens, out errors);
52+
if (errors.Length > 0)
53+
{
54+
WriteInvalidDataFileError(resolved, "CouldNotParseAsPowerShellDataFile");
55+
}
56+
else
57+
{
58+
var data = ast.Find(a => a is HashtableAst, false);
59+
if (data != null)
60+
{
61+
WriteObject(data.SafeGetValue());
62+
}
63+
else
64+
{
65+
WriteInvalidDataFileError(resolved, "CouldNotParseAsPowerShellDataFileNoHashtableRoot");
66+
}
67+
}
68+
}
69+
else
70+
{
71+
WritePathNotFoundError(path);
72+
}
73+
}
74+
}
75+
76+
private void WritePathNotFoundError(string path)
77+
{
78+
var errorId = "PathNotFound";
79+
var errorCategory = ErrorCategory.InvalidArgument;
80+
var errorMessage = string.Format(UtilityResources.PathDoesNotExist, path);
81+
var exception = new ArgumentException(errorMessage);
82+
var errorRecord = new ErrorRecord(exception, errorId, errorCategory, path);
83+
WriteError(errorRecord);
84+
}
85+
86+
void WriteInvalidDataFileError(string resolvedPath, string errorId)
87+
{
88+
var errorCategory = ErrorCategory.InvalidData;
89+
var errorMessage = string.Format(UtilityResources.CouldNotParseAsPowerShellDataFile, resolvedPath);
90+
var exception = new InvalidOperationException(errorMessage);
91+
var errorRecord = new ErrorRecord(exception, errorId, errorCategory, resolvedPath);
92+
WriteError(errorRecord);
93+
}
94+
}
95+
}

src/Modules/Shared/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psm1

Lines changed: 1 addition & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -321,62 +321,6 @@ function Format-Hex
321321

322322
}
323323

324-
## Imports a PowerShell Data File - a PowerShell hashtable defined in
325-
## a file (such as a Module manifest, session configuration file)
326-
function Import-PowerShellDataFile
327-
{
328-
[CmdletBinding(DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=623621")]
329-
[OutputType("System.Collections.Hashtable")]
330-
param(
331-
[Parameter(ParameterSetName = "ByPath", Position = 0)]
332-
[String[]] $Path,
333-
334-
[Parameter(ParameterSetName = "ByLiteralPath", ValueFromPipelineByPropertyName = $true)]
335-
[Alias("PSPath")]
336-
[String[]] $LiteralPath
337-
)
338-
339-
begin
340-
{
341-
function ThrowInvalidDataFile
342-
{
343-
param($resolvedPath, $extraError)
344-
345-
$errorId = "CouldNotParseAsPowerShellDataFile$extraError"
346-
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidData
347-
$errorMessage = [Microsoft.PowerShell.Commands.UtilityResources]::CouldNotParseAsPowerShellDataFile -f $resolvedPath
348-
$exception = [System.InvalidOperationException]::New($errorMessage)
349-
$errorRecord = [System.Management.Automation.ErrorRecord]::New($exception, $errorId, $errorCategory, $null)
350-
$PSCmdlet.WriteError($errorRecord)
351-
}
352-
}
353-
354-
process
355-
{
356-
foreach($resolvedPath in (Resolve-Path @PSBoundParameters))
357-
{
358-
$parseErrors = $null
359-
$ast = [System.Management.Automation.Language.Parser]::ParseFile(($resolvedPath.ProviderPath), [ref] $null, [ref] $parseErrors)
360-
if ($parseErrors.Length -gt 0)
361-
{
362-
ThrowInvalidDataFile $resolvedPath
363-
}
364-
else
365-
{
366-
$data = $ast.Find( { $args[0] -is [System.Management.Automation.Language.HashtableAst] }, $false )
367-
if($data)
368-
{
369-
$data.SafeGetValue()
370-
}
371-
else
372-
{
373-
ThrowInvalidDataFile $resolvedPath "NoHashtableRoot"
374-
}
375-
}
376-
}
377-
}
378-
}
379-
380324
## Converts a SDDL string into an object-based representation of a security
381325
## descriptor
382326
function ConvertFrom-SddlString
@@ -549,4 +493,4 @@ function ConvertFrom-SddlString
549493
RawDescriptor = $rawSecurityDescriptor
550494
}
551495
}
552-
}
496+
}

src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide",
1717
"Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData",
1818
"Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object",
1919
"Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable",
20-
"Clear-Variable", "Export-Clixml", "Import-Clixml", "ConvertTo-Xml", "Select-Xml", "Write-Debug",
20+
"Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile", "ConvertTo-Xml", "Select-Xml", "Write-Debug",
2121
"Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint",
2222
"Get-PSBreakpoint", "Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack",
2323
"Get-TraceSource", "Set-TraceSource", "Trace-Command", "Get-FileHash",

src/Modules/Windows-Core/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,13 @@ CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide",
1717
"Start-Sleep", "Tee-Object", "Measure-Command", "Update-TypeData", "Update-FormatData",
1818
"Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object",
1919
"Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable",
20-
"Clear-Variable", "Export-Clixml", "Import-Clixml", "ConvertTo-Xml", "Select-Xml", "Write-Debug",
20+
"Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile","ConvertTo-Xml", "Select-Xml", "Write-Debug",
2121
"Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint",
2222
"Get-PSBreakpoint", "Remove-PSBreakpoint", "New-TemporaryFile", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack",
2323
"Get-TraceSource", "Set-TraceSource", "Trace-Command", "Get-FileHash",
2424
"Unblock-File", "Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug",
2525
"Get-RunspaceDebug", "Wait-Debugger" , "Get-Uptime", "Get-Verb"
26-
FunctionsToExport= "Format-Hex", "Import-PowerShellDataFile", "ConvertFrom-SddlString"
26+
FunctionsToExport= "Format-Hex", "ConvertFrom-SddlString"
2727
AliasesToExport= "fhx"
2828
NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1"
2929
HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787'

src/Modules/Windows-Full/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,13 @@ CmdletsToExport= "Format-List", "Format-Custom", "Format-Table", "Format-Wide",
1919
"Start-Sleep", "Tee-Object", "Measure-Command", "Update-List", "Update-TypeData", "Update-FormatData",
2020
"Remove-TypeData", "Get-TypeData", "Write-Host", "Write-Progress", "New-Object", "Select-Object",
2121
"Group-Object", "Sort-Object", "Get-Variable", "New-Variable", "Set-Variable", "Remove-Variable",
22-
"Clear-Variable", "Export-Clixml", "Import-Clixml", "ConvertTo-Xml", "Select-Xml", "Write-Debug",
22+
"Clear-Variable", "Export-Clixml", "Import-Clixml", "Import-PowerShellDataFile", "ConvertTo-Xml", "Select-Xml", "Write-Debug",
2323
"Write-Verbose", "Write-Warning", "Write-Error", "Write-Information", "Write-Output", "Set-PSBreakpoint", "Get-PSBreakpoint",
2424
"Remove-PSBreakpoint", "Enable-PSBreakpoint", "Disable-PSBreakpoint", "Get-PSCallStack",
2525
"Send-MailMessage", "Get-TraceSource", "Set-TraceSource", "Trace-Command", "Show-Command", "Unblock-File", "Get-FileHash",
2626
"Get-Runspace", "Debug-Runspace", "Enable-RunspaceDebug", "Disable-RunspaceDebug", "Get-RunspaceDebug", "Wait-Debugger",
2727
"ConvertFrom-String", "Convert-String" , "Get-Uptime", "New-TemporaryFile", "Get-Verb"
28-
FunctionsToExport= "Format-Hex", "Import-PowerShellDataFile", "ConvertFrom-SddlString"
28+
FunctionsToExport= "Format-Hex", "ConvertFrom-SddlString"
2929
AliasesToExport= "CFS", "fhx"
3030
NestedModules="Microsoft.PowerShell.Commands.Utility.dll","Microsoft.PowerShell.Utility.psm1"
3131
HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=390787'

src/vs-csproj/Microsoft.PowerShell.Commands.Utility.csproj

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,12 @@
580580
<Compile Include="..\Microsoft.PowerShell.Commands.Utility\singleshell\installer\MshUtilityMshSnapin.cs">
581581
<Link>singleshell\installer\MshUtilityMshSnapin.cs</Link>
582582
</Compile>
583-
<Compile Include="commands\utility\GetVerbCommand.cs" />
583+
<Compile Include="..\Microsoft.PowerShell.Commands.Utility\commands\utility\GetVerbCommand.cs">
584+
<Link>commands\utility\GetVerbCommand.cs</Link>
585+
</Compile>
586+
<Compile Include="..\Microsoft.PowerShell.Commands.Utility\commands\utility\ImportPowerShellDataFile.cs">
587+
<Link>commands\utility\ImportPowerShellDataFile.cs</Link>
588+
</Compile>
584589
</ItemGroup>
585590
<ItemGroup>
586591
<None Include="..\Microsoft.PowerShell.Commands.Utility\map.json">

test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
}
1010
catch
1111
{
12-
$_.FullyQualifiedErrorId | Should be "PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand"
12+
$_.FullyQualifiedErrorId | Should be "PathNotFound,Microsoft.PowerShell.Commands.ImportPowerShellDataFileCommand"
1313
}
1414
}
1515

@@ -22,7 +22,7 @@
2222
}
2323
catch
2424
{
25-
$_.FullyQualifiedErrorId | Should be "CouldNotParseAsPowerShellDataFile,Import-PowerShellDataFile"
25+
$_.FullyQualifiedErrorId | Should be "PathNotFound,Microsoft.PowerShell.Commands.ImportPowerShellDataFileCommand"
2626
}
2727

2828
}
@@ -37,7 +37,7 @@
3737
}
3838
catch
3939
{
40-
$_.FullyQualifiedErrorId | Should be "InvalidOperationException,Import-PowerShellDataFile"
40+
$_.FullyQualifiedErrorId | Should be "System.InvalidOperationException,Microsoft.PowerShell.Commands.ImportPowerShellDataFileCommand"
4141
}
4242
}
4343

@@ -51,7 +51,7 @@
5151
}
5252
catch
5353
{
54-
$_.FullyQualifiedErrorId | Should be "CouldNotParseAsPowerShellDataFileNoHashtableRoot,Import-PowerShellDataFile"
54+
$_.FullyQualifiedErrorId | Should be "CouldNotParseAsPowerShellDataFileNoHashtableRoot,Microsoft.PowerShell.Commands.ImportPowerShellDataFileCommand"
5555
}
5656
}
5757

0 commit comments

Comments
 (0)