如果存在testfile1.log,请创建testfile2.log,依此类推.-PowerShell



我的PowerShell脚本创建了一个日志文件,但当我第二次运行该脚本时,它会告诉我testfile1.log文件已经存在。

如果它找到testfile1.log,它会创建testfile2.log,如果它也存在,它会生成testfile3.log,依此类推,我该如何制作脚本。

New-Item -Path $path -Name "testfile1.log" -ItemType "file"

您可以这样做,首先获取所需路径中的所有文件,并根据其名称上的结束数字对其进行排序。如果找不到文件,则创建testfile1.log;如果找到文件,则获取最后排序的文件(结尾数字最高的文件(提取结尾数字,并将+1添加到计数中,然后使用它创建新文件。

$files = Get-ChildItem $path -Filter testfile*.log | Sort-Object {
$_.BaseName -replace 'D' -as [int]
}
if(-not $files)
{
New-Item -Path $path -Name "testfile1.log" -ItemType File
}
else
{
[int]$number = $files[-1].BaseName -replace 'D'
$number++
New-Item -Path $path -Name "testfile$number.log" -ItemType File
}

基于这个答案的另一种方法可能是

$path  = 'D:Test'
$log   = 'testfile'
$index = ((Get-ChildItem -Path $path -Filter "$log*.log" -File |
Where-Object { $_.BaseName -match "$logd+$" } |
Select-Object @{Name = 'index'; Expression = {[int]($_.BaseName -replace 'D')}}).index |
Measure-Object -Maximum).Maximum + 1
# create the new file
New-Item -Path (Join-Path -Path $path -ChildPath "$log${index}.log") -ItemType File

一个简洁的解决方案,也建立在这个答案的基础上(有关核心技术的解释,请参阅此处(:

$path = '.'                       # Output dir.
$nameTemplate = 'testfile{0}.log' # {0} is the sequence-number placeholder
New-Item -ItemType File -Path $path -Name (
$nameTemplate -f (1 + (
# Find all existing log files
Get-ChildItem (Join-Path $path $nameTemplate.Replace('{0}', '*')) | 
Measure-Object -Maximum {
# Extract the embedded sequence number.
$_.Name -replace [regex]::Escape($nameTemplate).Replace('{0}', '(d+)'), '$1'
}
).Maximum)
) -WhatIf

注意:上面命令中的-WhatIf公共参数预览操作。一旦您确定操作将执行您想要的操作,请删除-WhatIf

注:

  • 以上使用复杂的-replace操作从现有文件名中可靠地提取序列号;如果您知道每个给定的文件名中只有一个编号,则$_.BaseName -replace 'D'(删除所有非数字字符(将在上面的Measure-Object调用中执行此操作。

  • 如果您想使用零填充、固定宽度序列号,您可以相应地调整(所有出现的({0}占位符;例如,创建序列号0102。。。99,使用{0:00}-请参阅复合格式帮助主题,该主题描述PowerShell的-f运算符也使用的字符串格式语言

最新更新