Randall Lee
Randall Lee

Reputation: 73

Loop string rename

I'm running a script that takes a screenshot and saves to file. I'm a novice and having trouble integrating mouse events so for now I'm going to complete part of my task manually.

$File = "C:\Users\mydirectory\image1.bmp"

Add-Type -AssemblyName System.Windows.Forms
Add-type -AssemblyName System.Drawing

Here is where I'm trying to add something to the effect of:

Do while $File -ne "C:\Users\mydirectory\image500.bmp"

I know that's not the right syntax but I'm stumped getting it to work.

# Gather Screen resolution information
$Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$Width = 2560
$Height = 1440
$Left = $Screen.Left
$Top = $Screen.Top

# Create bitmap using the top-left and bottom-right bounds
$bitmap = New-Object System.Drawing.Bitmap $Width, $Height

# Create Graphics object
$graphic = [System.Drawing.Graphics]::FromImage($bitmap)

# Capture screen
$graphic.CopyFromScreen($Left, $Top, 0, 0, $bitmap.Size)

# Save to file
$bitmap.Save($File) 

Write-Output "Screenshot saved to:"
Write-Output $File

This is where I'm lost. What I'm trying to accomplish here is to isolate the number on the end of the filename and add 1, looping until it reaches the number I have set above.

Start-Sleep -s 4

I have a sleep statement in my loop because I will be clicking the mouse manually.

Upvotes: 0

Views: 62

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

You can do something like this:

$i = 0
do {
  $i++
  $File = "C:\Users\mydirectory\image$i.bmp"
} until (-not (Test-Path -LiteralPath $File) -or $i -ge 500)

That increments the number ($i) until a non-existing filename is found or $i reaches 500.

Upvotes: 1

Related Questions