MyITGuy
10/2/2017 - 12:40 AM

PowerShell: Get-Win32ServicePathName

PowerShell: Get-Win32ServicePathName

function Get-Win32ServicePathName {
	[CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName="None")]
	PARAM(
	    [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName="p1")]
		[string[]]
		$PathName
	)
	
	begin {
	}
	
	process {
		foreach ($Path In $PathName) {
			switch ($true) {
				($Path -match '("([^"]+)")') {
					$Matches[2]
					break
				}
				($Path -match '(''([^'']+)'')') {
					$Matches[2]
					break
				}
				($Path -match '(^\S+)') {
					$Matches[0]
					break
				}
			}
		}
	}
	
	end {
	}
}
		#region Get-PathNameFromCommandLine
			function Get-PathNameFromCommandLine {
				[CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName="DefaultPS")]
				PARAM (
					[Alias("Path")]
					[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName="DefaultPS")]
					[AllowNull()]
					[AllowEmptyString()]
					[string[]]
					$PathName
				)
				
				begin {
				}
				
				process {
					foreach ($Path In $PathName) {
						# Modify the path so it can be cleaned-up correctly
						if ((Test-Path -Path $Path -PathType Leaf) -eq $true -and ($Path.StartsWith("`"") -eq $false -or $Path.StartsWith("`"") -eq $false)) {
							$Path = """$($Path)"""
						}
					
						switch ($true) {
							# Match double quoted path
							($Path -match '("([^"]+)")') {
								$Matches[2]
								break
							}
							# Match single quoted path
							($Path -match '("([^"]+)")') {
								$Matches[2]
								break
							}
							($Path -match '(''([^'']+)'')') {
								$Matches[2]
								break
							}
							($Path -match '(^\S+)') {
								$Matches[0]
								break
							}
						}
					}
				}
				
				end {
				}
			}
		#endregion Get-PathNameFromCommandLine