-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGet-AvailableFileName.ps1
47 lines (46 loc) · 1.29 KB
/
Get-AvailableFileName.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function Get-AvailableFileName
{
<#
.Synopsis
Gets an avaialble file name
.DESCRIPTION
Test a path to see if it exists. If a file already exists, it
will append '(x)' to the file name, where x is the next available number.
.EXAMPLE
Get-AvailableFileName -Path C:\Temp\SomeFilePath.txt
#>
[CmdletBinding()]
Param
(
# Specifies a path to one or more locations.
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[Alias("PSPath", "FullName")]
[ValidateNotNullOrEmpty()]
[string[]]
$Path
)
begin {}
process
{
foreach ($newName in $Path)
{
if (Test-Path -Path $newName)
{
$folder = Split-Path -Path $newName -Parent
$basename = [IO.Path]::GetFileNameWithoutExtension($newName)
$extension = [IO.Path]::GetExtension($newName)
$counter = 1
}
while (Test-Path -Path $newName)
{
$newName = "$($folder)\$($basename)($counter)$($extension)"
$counter++
}
Write-Output -InputObject $newName
}
}
end {}
}