2026年1月23日金曜日

ダウンロードフォルダを監視し RDP ファイルを自動で開く Powershell スクリプト

ダウンロードフォルダを監視し RDP ファイルを自動で開く Powershell スクリプト

概要

今の chrome ではできないので自作する必要があります

環境

  • Windows 11

ダウンロードフォルダを監視し特定の rdp ファイルが出現したら自動で実行する Powershell

  • vim monitor_rdp_file.ps1
param()

# Basic file logging to help diagnose scheduled task behavior
$logDir = Join-Path $env:LOCALAPPDATA "RDPFileMonitor"
if (-not (Test-Path $logDir)) {
    New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}
$logPath = Join-Path $logDir "monitor.log"
# Emit a simple startup marker regardless of transcript support
("Started: " + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) | Out-File -FilePath (Join-Path $logDir 'started.txt') -Append -Encoding utf8
try {
    Start-Transcript -Path $logPath -Append -ErrorAction SilentlyContinue | Out-Null
} catch {}

$downloadFolder = [Environment]::GetFolderPath("UserProfile") + "\Downloads"
$targetRDPFileName = "your-rdp-filename.rdp"
$processedFiles = @()

Write-Host "Starting RDP file monitoring (polling method)"
Write-Host "Log: $logPath"
Write-Host "Target folder: $downloadFolder"
Write-Host "Target file name: $targetRDPFileName"
Write-Host "Checking every 2 seconds..."

while ($true) {
    try {
        if (Test-Path $downloadFolder) {
            $files = Get-ChildItem -Path $downloadFolder -Filter "*.rdp" -File
            
            foreach ($file in $files) {
                if ($file.Name -eq $targetRDPFileName -and $file.FullName -notin $processedFiles) {
                    Write-Host "Target file detected: $($file.Name) at $(Get-Date -Format 'HH:mm:ss')"
                    Write-Host "Full path: $($file.FullName)"
                    
                    Start-Sleep -Seconds 2
                    
                    try {
                        Write-Host "Executing RDP file: $($file.FullName)"
                        # Use Start-Process for reliability in scheduled tasks
                        Start-Process -FilePath $file.FullName
                        $processedFiles += $file.FullName
                        Write-Host "Executed successfully"
                        
                        Start-Sleep -Seconds 1
                        Remove-Item -Path $file.FullName -Force
                        Write-Host "File deleted: $($file.FullName)"
                    }
                    catch {
                        Write-Error "Error executing RDP file: $($_.Exception.Message)"
                    }
                }
            }
        }
    }
    catch {
        Write-Error "Error during monitoring: $($_.Exception.Message)"
    }
    
    Start-Sleep -Seconds 2
}
finally {
    try { Stop-Transcript | Out-Null } catch {}
}

上記ファイルを実行する bat ファイル

権限を付与して実行する必要があるのでラッパー用のバッチファイルを作成します

  • vim monitor_rdp_file.bat
@echo off
REM This batch file launches the RDP file monitor PowerShell script
REM It will be called by Task Scheduler at user login

REM Ensure we start in the script directory (useful for relative paths)
pushd "C:\Users\username\path\to\powershell_script\"

REM Prepare simple logs for troubleshooting
set "LOGDIR=%LOCALAPPDATA%\RDPFileMonitor"
if not exist "%LOGDIR%" mkdir "%LOGDIR%" >nul 2>&1

REM Launch the PowerShell monitor hidden with execution policy bypass and redirect output to logs
powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "C:\Users\username\path\to\powershell_script\monitor_rdp_file.ps1" 1>>"%LOGDIR%\ps_out.log" 2>>"%LOGDIR%\ps_err.log"

popd
exit /b 0

バッチファイルをタスクスケジューラに登録する Powershell

タスクスケジューラで動かす場合はバッチファイルを登録します

  • vim register_scheduled_task.ps1
# Create scheduled task for RDP file monitor at user login
# This script should be run with administrator privileges

$taskName = "RDP File Monitor"
$taskPath = "\"
$scriptPath = "C:\Users\username\path\to\powershell_script\monitor_rdp_file.bat"

Write-Host "Creating scheduled task for RDP file monitor..."

# Check if task already exists
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue

if ($existingTask) {
    Write-Host "Task already exists. Removing..."
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
}

# Create task trigger (at user login)
$trigger = New-ScheduledTaskTrigger -AtLogOn

# Create task action
$workingDir = Split-Path -Path $scriptPath -Parent
$action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c `"$scriptPath`"" -WorkingDirectory $workingDir

# Create task settings
$settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -StartWhenAvailable

# Register the task with highest privilege
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERNAME" -RunLevel Highest -LogonType Interactive

Register-ScheduledTask -TaskName $taskName -Trigger $trigger -Action $action -Settings $settings -Principal $principal -Force

Write-Host "Task created successfully!"
Write-Host "Task name: $taskName"
Write-Host "Batch file: $scriptPath"
Write-Host "Trigger: At user login"
Write-Host ""
Write-Host "The task will now run automatically when you log in to Windows."

タスクスケジューラ登録

Start-Process powershell.exe -ArgumentList "-ExecutionPolicy Bypass -Command `"& 'C:\Users\username\path\to\powershell_script\register_scheduled_task.ps1'`"" -Verb RunAs -Wait

最後に

これでログインすると自動で起動し監視を開始します
cmdkey などと組み合わせると自動でログインまでしてくれます
ただ rdp ファイルの prompt for credentials:i:1 が 0 になっていないとダメです
(1 でも自動入力する方法はないのだろうか)

0 件のコメント:

コメントを投稿