我的 PowerShell 腳本創建了一個日志檔案,但是當我第二次運行該腳本時,它告訴我 testfile1.log 檔案已經存在。
如果找到 testfile1.log,我如何制作腳本,它會創建 testfile2.log,如果這也存在,它會創建 testfile3.log,依此類推..
New-Item -Path $path -Name "testfile1.log" -ItemType "file"
uj5u.com熱心網友回復:
您可以這樣做,首先獲取所需路徑中的所有檔案,然后按名稱的結尾數字對它們進行排序。如果沒有找到檔案,則創建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
}
uj5u.com熱心網友回復:
一個簡潔的解決方案也建立在這個答案之上(參見那里對核心技術的解釋):
$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}相應地調整(所有出現的)占位符;例如,要創建序列號01,02, ...99,請使用{0:00}- 請參閱復合格式化幫助主題,該主題描述了 PowerShell-f運算子也使用的字串格式化語言
uj5u.com熱心網友回復:
基于此答案的另一種方法可能是
$path = 'D:\Test'
$log = 'testfile'
$index = ((Get-ChildItem -Path $path -Filter "$log*.log" -File |
Where-Object { $_.BaseName -match "$log\d $" } |
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/412540.html
標籤:
下一篇:匯出為CSV不帶標題或引號
