powershell - 使用循环找不到更好的解决方案
问题描述
我在 PowerShell 中有一个任务检查文件的名称,如果它存在,则在末尾添加数字,如果在第一次检查后存在,我们将数字加一。
我无法将数字增加 1。
$path = 'D:\Test\TestFile.zip'
if (Test-Path $path) {
# File exists, append number
$fileSeed = 0
do {
$path = $path -replace ".zip$"
$path += ''
$fileSeed++
$path = "$path$fileSeed.zip"
} until ( ! (Test-Path $path) )
} else {
$path
}
解决方案
前段时间,我为它写了一个小函数,叫做Get-UniqueFileName
.
function Get-UniqueFileName {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, Position = 0)]
[Alias('FullName')]
[string]$Path
)
$directory = [System.IO.Path]::GetDirectoryName($Path)
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($Path)
$extension = [System.IO.Path]::GetExtension($Path) # this includes the dot
# get an array of all files with the same extension currently in the directory
$allFiles = @(Get-ChildItem $directory -File -Filter "$baseName*$extension" | Select-Object -ExpandProperty Name)
# construct the possible new file name (just the name, not hte full path and name)
$newFile = $baseName + $extension
$seed = 1
while ($allFiles -contains $newFile) {
# add the seed value between brackets. (you can ofcourse leave them out if you like)
$newFile = "{0}({1}){2}" -f $baseName, $seed, $extension
$seed++
}
# return the full path and filename
return Join-Path -Path $directory -ChildPath $newFile
}
像这样使用它:
Get-UniqueFileName -Path 'D:\Test\TestFile.zip'
如果目录D:\Test
已经包含一个名为的文件TestFile.zip
和另一个名为的文件TestFile(1).zip
,它将返回D:\Test\TestFile(2).zip
推荐阅读
- python - django:在 Drinkdatabase 中按成分搜索
- netlogo - 迭代布尔值列表
- sql - 有没有办法使用 SQL 而不是 SPL 访问 Splunk?
- appcelerator - 构建到 iOS 设备:DTDeviceKit:deviceType from
为空 - docker - Vuejs nginx dockerised 应用程序无法与 docker-compose 一起使用
- android - 通过意图发送电子邮件与无意图发送电子邮件
- xamarin - ImagePicker MainActivity Instance is not defined
- node.js - 猫鼬批量执行创建,如果不存在,否则更新不包含时间戳
- python - 如何在python中的unix时间戳中获取当前日期时间
- java - Fedora 30 和 OpenJDK 1.8.0_212:java.lang.OutOfMemoryError:无法创建新的本机线程