You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在IIS 8.5中监控FTP上传并自动触发PowerShell脚本

How to Trigger Image Optimization for Specific FTP Accounts on IIS 8.5 (Windows Server 2012 R2)

Absolutely, you can pull this off—and there’s a far more precise, reliable approach than the timed FileSystemWatcher batch method you dismissed. Instead of polling folders, we’ll tie IIS FTP’s built-in event logging directly to your PowerShell script, ensuring we only trigger optimization when your specified FTP account successfully uploads a JPG or PNG. Here’s how to set it up:

Step 1: Configure IIS FTP to Log Critical Upload Details

First, make sure your FTP site captures the data we need to target the right events:

  1. Open IIS Manager, navigate to your target FTP site.
  2. Go to Logging in the site features view.
  3. For the log format, select W3C and ensure these fields are checked:
    • cs-username (tracks the FTP account)
    • cs-method (we’ll look for STOR, the FTP upload command)
    • cs-uri-stem (the uploaded file path/name)
    • sc-status (confirms upload success via code 226)
  4. Note your log storage path (default: %SystemDrive%\inetpub\logs\LogFiles\FTPSVCx where x is your site’s ID).

We’ll also need to enable IIS FTP’s Operational Event Log (if not already active):

  • Open Event Viewer → Navigate to Applications and Services Logs > Microsoft > Windows > FTP-Service > Operational
  • Right-click the log and select Enable Log—this generates structured events for successful uploads.

Step 2: Create a Task Scheduler Trigger for FTP Upload Events

Windows Task Scheduler can watch for specific FTP events and run your script in real time, which is way more stable than custom polling scripts:

  1. Open Task Scheduler → Create Task (not a basic task, for advanced filtering).
  2. On the General tab:
    • Name the task (e.g., "FTP Image Optimizer for [Your Account]")
    • Check "Run whether user is logged on or not" and "Run with highest privileges"
  3. On the Triggers tab:
    • Click New → Select On an event from the dropdown.
    • For the log, choose Microsoft-Windows-FTP-Service/Operational
    • For the source, choose Microsoft-Windows-FTP-Service
    • Click Edit Event Filter → Switch to the XML tab, check "Edit query manually", and paste this modified query (replace YOUR_TARGET_FTP_USER with your account name):
      <QueryList>
        <Query Id="0" Path="Microsoft-Windows-FTP-Service/Operational">
          <Select Path="Microsoft-Windows-FTP-Service/Operational">*[System[Provider[@Name='Microsoft-Windows-FTP-Service'] and EventID=10]] and *[EventData[Data[@Name='UserName']='YOUR_TARGET_FTP_USER'] and Data[@Name='FileName']=~'.*\.(jpg|png)$']</Select>
        </Query>
      </QueryList>
      
    • This filters for Event ID 10 (successful file upload), your target FTP account, and files ending in .jpg/.png.
  4. On the Actions tab:
    • Click New → Select Start a program.
    • For "Program/script", enter powershell.exe
    • For "Add arguments", enter:
      -ExecutionPolicy Bypass -File "C:\Path\To\Your\Optimize-Images.ps1" -FilePath "%EventData[FileName]%"
      
    • This passes the uploaded file path directly to your optimization script.

Step 3: Refine Your PowerShell Optimization Script

Update your existing script to accept the uploaded file path as a parameter, and ensure it handles the file safely. Here’s a minimal example (swap in your preferred optimization logic—ImageMagick, .NET’s System.Drawing, or a dedicated tool like jpegoptim):

param(
    [Parameter(Mandatory=$true)]
    [string]$FilePath
)

# Validate the file exists and is a target image type
if (-not (Test-Path -Path $FilePath -PathType Leaf) -or $FilePath -notmatch '\.(jpg|png)$') {
    Write-Error "Invalid or missing file: $FilePath"
    exit 1
}

# Example: Use ImageMagick to compress JPG/PNG (install ImageMagick first)
$imageMagickPath = "C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\convert.exe"
if (Test-Path $imageMagickPath) {
    # Compress JPG to 80% quality; adjust parameters for PNG as needed
    & $imageMagickPath $FilePath -quality 80 $FilePath
    Write-Host "Successfully optimized: $FilePath"
} else {
    Write-Error "ImageMagick not found at $imageMagickPath"
    exit 1
}

Why This Is Better Than FileSystemWatcher

  • Account-specific triggers: No more processing files uploaded by other users or local system operations.
  • Guaranteed complete uploads: Event ID 10 only fires after the FTP service confirms the upload finished, so you won’t try to optimize a partially written file.
  • Server-grade stability: Task Scheduler is built into Windows and handles crashes/retries better than custom PowerShell loops.

Testing the Setup

  1. Log in with your target FTP account and upload a JPG/PNG.
  2. Check Task Scheduler’s History tab to confirm the task triggered.
  3. Verify the file was optimized (check file size, quality, etc.).

内容的提问来源于stack exchange,提问作者Strontium_99

火山引擎 最新活动