Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
2771c85
Add Get-Uri function for URI conversion and normalization
MariusStorhaug Feb 8, 2025
71e0d3d
Refactor parameter declaration to use lowercase 'param' in Get-Uri fu…
MariusStorhaug Feb 8, 2025
627cc4e
Add tests for Get-Uri function covering default behavior, error handl…
MariusStorhaug Feb 8, 2025
0e3ebb6
Enhance Get-Uri function tests to cover edge cases for relative URIs,…
MariusStorhaug Feb 8, 2025
5f0af3c
Fix Get-Uri tests to correctly validate query strings and fragments
MariusStorhaug Feb 8, 2025
ebf8c67
Improve error handling in Get-Uri tests for relative URIs by adding v…
MariusStorhaug Feb 8, 2025
eb434bc
Add jscpd configuration for duplicate code detection
MariusStorhaug Feb 8, 2025
5f164f6
Disable JSON validation in Linter workflow
MariusStorhaug Feb 8, 2025
b67dbc0
Add verbose output to Get-Uri tests for improved debugging
MariusStorhaug Feb 8, 2025
7ed8f14
Remove redundant tests and streamline Get-Uri test cases for clarity
MariusStorhaug Feb 8, 2025
c1445eb
Update Get-Uri example to reflect correct output for path parameter
MariusStorhaug Feb 9, 2025
94e042c
Refactor Get-Uri function to improve parameter handling and support r…
MariusStorhaug Feb 9, 2025
1d80624
Enhance Get-Uri documentation with detailed output examples and clari…
MariusStorhaug Feb 9, 2025
21e4573
Add Test-Uri function to validate URI strings with optional relative …
MariusStorhaug Feb 9, 2025
86eb538
Update Test-Uri documentation for consistency in output examples
MariusStorhaug Feb 9, 2025
2c382a4
Refactor ConvertFrom-UriQueryString function and update test cases fo…
MariusStorhaug Feb 9, 2025
9dd644e
Refactor Get-Uri function to streamline parameter handling and improv…
MariusStorhaug Feb 9, 2025
be31960
Add verbose output for test results in Uri.Tests to enhance debugging…
MariusStorhaug Feb 9, 2025
fd1faec
Update test output in Uri.Tests to use Get-Uti for improved clarity i…
MariusStorhaug Feb 9, 2025
e2877db
Refactor ConvertFrom-UriQueryString parameter handling and update Tes…
MariusStorhaug Feb 9, 2025
4c788b1
Refactor URI test cases for improved clarity and consistency; update …
MariusStorhaug Feb 9, 2025
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
10 changes: 10 additions & 0 deletions .github/linters/.jscpd.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"threshold": 0,
"reporters": [
"consoleFull"
],
"ignore": [
"**/tests/*"
],
"absolute": true
}
1 change: 1 addition & 0 deletions .github/workflows/Linter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ jobs:
GITHUB_TOKEN: ${{ github.token }}
VALIDATE_MARKDOWN_PRETTIER: false
VALIDATE_YAML_PRETTIER: false
VALIDATE_JSON_PRETTIER: false
10 changes: 3 additions & 7 deletions src/functions/public/ConvertFrom-UriQueryString.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
back to their normal representation.

.EXAMPLE
ConvertFrom-UriQueryString -QueryString 'name=John%20Doe&age=30&age=40'
ConvertFrom-UriQueryString -Query 'name=John%20Doe&age=30&age=40'

Output:
```powershell
Expand All @@ -25,7 +25,7 @@
values are decoded parameter values.

.EXAMPLE
ConvertFrom-UriQueryString '?q=PowerShell%20URI'
'?q=PowerShell%20URI' | ConvertFrom-UriQueryString

Output:
```powershell
Expand All @@ -44,12 +44,11 @@
param(
# The query string to parse. This can include the leading '?' or just the key-value pairs.
# For example, both "?foo=bar&count=10" and "foo=bar&count=10" are acceptable.
[Parameter(Position = 0, ValueFromPipeline)]
[Parameter(ValueFromPipeline)]
[AllowNull()]
[string] $Query
)

# Early exit if $Query is null or empty.
if ([string]::IsNullOrEmpty($Query)) {
Write-Verbose 'Query string is null or empty.'
return @{}
Expand All @@ -60,9 +59,6 @@
if ($Query.StartsWith('?')) {
$Query = $Query.Substring(1)
}
if ([string]::IsNullOrEmpty($Query)) {
return @{} # return empty hashtable if no query present
}

$result = @{}
# Split by '&' to get each key=value pair
Expand Down
134 changes: 134 additions & 0 deletions src/functions/public/Get-Uri.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
function Get-Uri {
<#
.SYNOPSIS
Converts a string into a System.Uri, System.UriBuilder, or a normalized URI string.

.DESCRIPTION
The Get-Uri function processes a string and attempts to convert it into a valid URI.
It supports three output formats: a System.Uri object, a System.UriBuilder object,
or a normalized absolute URI string. If no scheme is present, "http://" is prefixed
to ensure a valid URI. The function enforces mutual exclusivity between the output
format parameters.

.EXAMPLE
Get-Uri -Uri 'example.com'

Output:
```powershell
AbsolutePath : /
AbsoluteUri : http://example.com/
LocalPath : /
Authority : example.com
HostNameType : Dns
IsDefaultPort : True
IsFile : False
IsLoopback : False
PathAndQuery : /
Segments : {/}
IsUnc : False
Host : example.com
Port : 80
Query :
Fragment :
Scheme : http
OriginalString : http://example.com
DnsSafeHost : example.com
IdnHost : example.com
IsAbsoluteUri : True
UserEscaped : False
UserInfo :
```

Converts 'example.com' into a normalized absolute URI string.

.EXAMPLE
Get-Uri -Uri 'https://example.com/path' -AsUriBuilder

Output:
```powershell
Scheme : https
UserName :
Password :
Host : example.com
Port : 443
Path : /path
Query :
Fragment :
Uri : https://example.com/path
```

Returns a [System.UriBuilder] object for the specified URI.

.EXAMPLE
'example.com/path' | Get-Uri -AsString

Output:
```powershell
http://example.com/path
```

Returns a [string] with the full absolute URI.

.LINK
https://psmodule.io/Uri/Functions/Get-Uri
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSReviewUnusedParameter', 'AsString',
Scope = 'Function',
Justification = 'Present for parameter sets'
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSReviewUnusedParameter', 'AsUriBuilder',
Scope = 'Function',
Justification = 'Present for parameter sets'
)]
[OutputType(ParameterSetName = 'UriBuilder', [System.UriBuilder])]
[OutputType(ParameterSetName = 'String', [string])]
[OutputType(ParameterSetName = 'AsUri', [System.Uri])]
[CmdletBinding(DefaultParameterSetName = 'AsUri')]
param(
# The string representation of the URI to be processed.
[Parameter(Mandatory, Position = 0, ValueFromPipeline)]
[string] $Uri,

# Outputs a System.UriBuilder object.
[Parameter(Mandatory, ParameterSetName = 'AsUriBuilder')]
[switch] $AsUriBuilder,

# Outputs the URI as a normalized string.
[Parameter(Mandatory, ParameterSetName = 'AsString')]
[switch] $AsString
)

process {
$inputString = $Uri.Trim()
if ([string]::IsNullOrWhiteSpace($inputString)) {
throw 'The Uri parameter cannot be null or empty.'
}

# Attempt to create a System.Uri (absolute) from the string
$uriObject = $null
$success = [System.Uri]::TryCreate($inputString, [System.UriKind]::Absolute, [ref]$uriObject)
if (-not $success) {
# If no scheme present, try adding "http://"
if ($inputString -notmatch '^[A-Za-z][A-Za-z0-9+.-]*:') {
$success = [System.Uri]::TryCreate("http://$inputString", [System.UriKind]::Absolute, [ref]$uriObject)
}
if (-not $success) {
throw "The provided value '$Uri' cannot be converted to a valid URI."
}
}

switch ($PSCmdlet.ParameterSetName) {
'AsUriBuilder' {
return ([System.UriBuilder]::new($uriObject))
}
'AsString' {
return ($uriObject.GetComponents([System.UriComponents]::AbsoluteUri, [System.UriFormat]::SafeUnescaped))
}
'AsUri' {
return $uriObject
}
}
}
}
75 changes: 75 additions & 0 deletions src/functions/public/Test-Uri.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
function Test-Uri {
<#
.SYNOPSIS
Validates whether a given string is a valid URI.

.DESCRIPTION
The Test-Uri function checks whether a given string is a valid URI. By default, it enforces absolute URIs.
If the `-AllowRelative` switch is specified, it allows both absolute and relative URIs.

.EXAMPLE
Test-Uri -Uri "https://example.com"

Output:
```powershell
True
```

Checks if `https://example.com` is a valid URI, returning `$true`.

.EXAMPLE
Test-Uri -Uri "invalid-uri"

Output:
```powershell
False
```

Returns `$false` for an invalid URI string.

.EXAMPLE
"https://example.com", "invalid-uri" | Test-Uri

Output:
```powershell
True
False
```

Accepts input from the pipeline and validates multiple URIs.

.OUTPUTS
[System.Boolean]

.NOTES
Returns `$true` if the input string is a valid URI, otherwise returns `$false`.

.LINK
https://psmodule.io/Uri/Functions/Test-Uri
#>
[OutputType([bool])]
[CmdletBinding()]
param(
# Accept one or more URI strings from parameter or pipeline.
[Parameter(Mandatory, ValueFromPipeline)]
[string] $Uri,

# If specified, allow valid relative URIs.
[Parameter()]
[switch] $AllowRelative
)

process {
# If -AllowRelative is set, try to create a URI using RelativeOrAbsolute.
# Otherwise, enforce an Absolute URI.
$uriKind = if ($AllowRelative) {
[System.UriKind]::RelativeOrAbsolute
} else {
[System.UriKind]::Absolute
}

# Try to create the URI. The out parameter is not used.
$dummy = $null
[System.Uri]::TryCreate($Uri, $uriKind, [ref]$dummy)
}
}
Loading