这样可以做到:
Function Move-PTIFile {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Origin,
[Parameter(Mandatory = $true, Position = 1)]
[string]$Destination,
[switch]$CreateDirectory
)
# see if the destination exists
if (!(Test-Path $Destination -PathType Container)) {
if (!($CreateDirectory)) {
Write-Error "Folder '$Destination' does not exist.`r`nPlease create folder or flag CreateDirectory parameter as true."
return
}
Write-Verbose -Message "Creating folder '$Destination'"
New-Item -Path $Destination -ItemType Directory -Force | Out-Null
}
# check if a file with that name already exists within the destination
$fileName = Join-Path $Destination ([System.IO.Path]::GetFileName($Origin))
if (Test-Path $fileName -PathType Leaf){
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($Origin)
$extension = [System.IO.Path]::GetExtension($Origin) # this includes the dot
$allFiles = Get-ChildItem $Destination | Where-Object {$_.PSIsContainer -eq $false} | Foreach-Object {$_.Name}
$newName = $baseName + $extension
$count = 1
while ($allFiles -contains $newName) {
$newName = [string]::Format("{0}({1}){2}", $baseName, $count.ToString(), $extension)
$count++
}
# rename the file already in the destination folder
Write-Verbose -Message "Renaming file '$fileName' to '$newName'"
Rename-Item $fileName -NewName $newName
}
Write-Verbose -Message "Moving file '$Origin' to folder '$Destination'"
Move-Item $Origin $Destination
}
############## TESTING ##############
$Origin = "C:\MyFiles\Temp\Test.txt"
$Destination = "C:\MyFiles\Temp\Movedd\Test\Testing\Testttt"
Move-PTIFile $Origin $Destination -Verbose