Created
June 28, 2018 01:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.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