xlogI125’s blog

パソコン作業を効率化したい

プリンタードライバーが作成した電子文書ファイルをフォルダ監視で印刷

メモ

  • FileSystemWatcherクラス と Register-ObjectEventコマンドレット を使用
  • 印刷はコマンド入力に対応したビューアーを使用

プリンターのドライバー名とポート名

CIMクラスの一覧から特定の文字列を含むものを選択

Get-CimClass | Where-Object -Property CimClassName -Match '.*Printer.*' | Format-List -Property *

プリンターのドライバー名とポート名を表示

Get-CimInstance -ClassName CIM_Printer | Select-Object -Property Name, DriverName, PortName | Format-Table -Wrap

使い捨てスクリプト

  • 誤操作防止を気にしていないので練習以外で使用しない

ビューアーのコマンド入力で印刷

  • 透過部分が入っている電子文書ファイルをフォルダに貼り付けた場合の対応は気にしない
# PowerShell 5.1, Windows 11 (2023年6月頃)

Set-StrictMode -Version Latest

$ErrorActionPreference = "Stop"
$VerbosePreference = "Continue"

try {
  $watcher              = [IO.FileSystemWatcher]::new()
  $watcher.Path         = "${env:USERPROFILE}\Desktop"
  $watcher.Filter       = "*.?dw"
  $watcher.NotifyFilter = [IO.NotifyFilters]::FileName

  $pathViewer = (Resolve-Path -Path 'C:\Program Files*\*\*\bin\*viewer.exe').Path
  Write-Verbose $pathViewer

  Register-ObjectEvent -InputObject $watcher -EventName "Created" -Action {
    Write-Verbose $EventArgs.FullPath
    Start-Process -FilePath $pathViewer -ArgumentList @(
      '"' + $($EventArgs.FullPath) + '"'
      '/pt'
      '"Microsoft Print To PDF"'  # 名前
      '"Microsoft Print To PDF"'  # モデル
      '"PORTPROMPT:"'             # ポート
    )
  }
}
catch {
  throw $_
}

Get-Job | Format-List

デスクトップに作成されたファイルを監視

# PowerShell 5.1, Windows 11 (2023年6月頃)

Set-StrictMode -Version Latest

$watcher = [IO.FileSystemWatcher]::new()
$watcher.Path = "${env:USERPROFILE}\Desktop"
$watcher.IncludeSubdirectories = $true
$watcher.Filter = "*.*"
$watcher.NotifyFilter = 
  [IO.NotifyFilters]::FileName -bor 
  [IO.NotifyFilters]::DirectoryName -bor 
  [IO.NotifyFilters]::Size -bor 
  [IO.NotifyFilters]::CreationTime -bor 
  [IO.NotifyFilters]::LastWrite -bor 
  [IO.NotifyFilters]::LastAccess -bor 
  [IO.NotifyFilters]::Attributes -bor 
  [IO.NotifyFilters]::Security
$watcher.EnableRaisingEvents = $true

$action = {
  Write-Host "**********"
  Get-Date | Write-Host
  Write-Host $EventSubscriber.EventName
  Write-Host $Event.SourceEventArgs.FullPath
}

Register-ObjectEvent -InputObject $watcher -EventName "Created" -Action $action
Register-ObjectEvent -InputObject $watcher -EventName "Deleted" -Action $action

Add-Type -Language CSharp -TypeDefinition @'
namespace MyNS {
  public class MyClass {
    public static void MyAddEventChanged(System.IO.FileSystemWatcher watcher) {
      watcher.Changed += (object sender, System.IO.FileSystemEventArgs e) => {
        System.Console.WriteLine("----------");
        System.Console.WriteLine("{0}", System.DateTime.Now.ToString());
        System.Console.WriteLine("{0}", e.ChangeType.ToString());
        System.Console.WriteLine("{0}", e.FullPath);
      };
    }
  }
}
'@

[MyNS.MyClass]::MyAddEventChanged($watcher)

Get-EventSubscriber