【问题标题】:PowerShell finding a file and creating a new onePowerShell 查找文件并创建新文件
【发布时间】:2014-08-24 06:06:34
【问题描述】:

我正在处理的脚本每次运行时都会生成一个日志文件。问题是当脚本并行运行时,Out-File 无法访问当前日志文件。这是正常的,因为之前的脚本还在里面写。

所以我希望脚本能够在启动时检测到已经有可用的日志文件,如果有,请创建一个新的日志文件名,在括号[<nr>] 之间增加数字。

很难检查一个文件是否已经存在,因为每次脚本启动时它都可能有另一个数字。如果它可以在括号中选取该数字并使用 +1 递增作为新文件名,那就太好了。

代码:

$Server = "UNC"
$Destination ="\\domain.net\share\target\folder 1\folder 22"
$LogFolder = "\\server\c$\my logfolder"

# Format log file name
$TempDate = (Get-Date).ToString("yyyy-MM-dd")
$TempFolderPath = $Destination -replace '\\','_'
$TempFolderPath = $TempFolderPath -replace ':',''
$TempFolderPath = $TempFolderPath -replace ' ',''
$script:LogFile = "$LogFolder\$(if($Server -ne "UNC"){"$Server - $TempFolderPath"}else{$TempFolderPath.TrimStart("__")})[0] - $TempDate.log"
$script:LogFile

# Create new log file name
$parts = $script:LogFile.Split('[]')
$script:NewLogFile = '{0}[{1}]{2}' -f $parts[0],(1 + $parts[1]),$parts[2]
$script:NewLogFile

# Desired result
# \\server\c$\my logfolder\domain.net_share_target_folder1_folder22[0] - 2014-07-30.log
# \\server\c$\my logfolder\domain.net_share_target_folder1_folder22[1] - 2014-07-30.log
#
# Usage
# "stuff" | Out-File -LiteralPath $script:LogFile -Append

【问题讨论】:

  • 感谢 Ansgar 的帮助。但我有点困惑。在我的示例中,我尝试使用 nr 创建一个初始日志文件。 [0] 在里面。当我将它与Out-File 一起使用时,这会失败,因为我似乎无法正确地转义括号。如果我设法做到这一点,那么我如何只检查最新的号码以添加+1?因为当脚本关闭并运行下一个脚本时,示例中的变量 $filename 将丢失。
  • -LiteralPath 应该注意方括号。请显示您遇到的错误。至于丢失$filename 的值:我的代码示例中的循环将自动找到给定名称模式foo[#]bar.log 的最小未使用数字#。如果目标文件夹中已经存在foo[0]bar.logfoo[1]bar.log,则循环将生成foo[2]bar.log 作为下一个文件名。
  • 您的代码确实在$filename 内的固定值上工作。我现在正试图弄清楚如何检索驱动器上的现有文件名并将其放入$filename 变量中。当然只适用于名称中具有正确$DestinationGet-Date 的人。
  • 我把事情复杂化了,它按设计工作。谢谢 Ansgar,这真的很有帮助。我会用你的解决方案更新我的问题。再次感谢伙计!

标签: variables powershell file-io


【解决方案1】:

my answer to your previous question 中所述,您可以使用以下方式自动增加文件名中的数字:

while (Test-Path -LiteralPath $script:LogFile) {
  $script:LogFile = Increment-Index $script:LogFile
}

其中Increment-Index 实现了将文件名中的索引加一的程序逻辑,例如像这样:

function Increment-Index($f) {
  $parts = $f.Split('[]')
  '{0}[{1}]{2}' -f $parts[0],(1 + $parts[1]),$parts[2]
}

或者像这样:

function Increment-Index($f) {
  $callback = {
    $v = [int]$args[0].Groups[1].Value
    $args[0] -replace $v,++$v
  }

  ([Regex]'\[(\d+)\]').Replace($f, $callback)
}

while 循环增加索引直到它产生一个不存在的文件名。条件中的参数-LiteralPath是必需的,因为文件名包含方括号,否则会被视为wildcard characters

【讨论】:

  • 太棒了!第一个更容易阅读。其他人唯一缺少的就是在Increment-Index 之前添加单词Function。再次感谢伙计! :)
  • @DarkLite1 已修复。感谢您的提醒。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多