Skip to content

Instantly share code, notes, and snippets.

@techthoughts2
Created June 28, 2018 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techthoughts2/49960265aef995179bbb257c5f4ca18b to your computer and use it in GitHub Desktop.
Save techthoughts2/49960265aef995179bbb257c5f4ca18b to your computer and use it in GitHub Desktop.
PowerShell function that takes a fully provided path to a file and returns just the file name of that path
<#
.Synopsis
Returns file name from full file path
.DESCRIPTION
Takes a fully provided path to a file and returns just the file name of that path
.EXAMPLE
Get-FileName -FilePath C:\afolder\afile.txt
Returns just the filename from the fully provided path
.EXAMPLE
Get-FileName -FilePath $ImagePath -Verbose
Returns just the filename from the fully provided path in $ImagePath with verbose output
.PARAMETER FilePath
Full file sytem path to specified file
.OUTPUTS
System.String
.NOTES
Author: Jake Morrison - @jakemorrison - http://techthoughts.info/
#>
function Get-FileName {
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true,
HelpMessage = 'Full path to file')]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[string]$FilePath
)
Write-Verbose -Message "Processing $FilePath ..."
#-------------------------------------------------
#$divide = $FilePath.Split("\")
#$fileName = $divide[$divide.Length - 1]
#$results = $fileName
#-------------------------------------------------
$results = ""
try {
$fileInfo = Get-ChildItem -Path $FilePath -ErrorAction Stop
$fileName = $fileInfo.Name
Write-Verbose -Message "Filename is: $fileName"
$results = $fileName
}#try_Get-ChildItem
catch {
Write-Warning "The file information for $FilePath could not be determined."
$results = "ERROR"
}#catch_Get-ChildItem
return $results
}#function_Get-FileName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment