title: PowerShell finding a file and creating a new one
body: <p>The script I'm working on is producing a log file every time it runs. The problem is that when the script runs in parallel, the current log file becomes inaccessible for <code>Out-File</code>. This is normal because the previous script is still writing in it. </p>
  
  <p>So I would like the script being able to detect, when it starts, that there is already a log file available, and if so, create a new log file name with an increased number between the brackets <code>[&lt;nr&gt;]</code>. </p>
  
  <p>It's very difficult to check if a file already exists, as it can have another number each time the script starts. It would be great if it could then pick up that number between the brackets and increment it with <code>+1</code> for the new file name.</p>
  
  <p><strong>The code:</strong></p>
  
  <pre><code>$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
  </code></pre>