1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShell 7でクリップボードのファイル操作

1
Last updated at Posted at 2020-09-22

消えたと思われていたコマンドレットの Get-Clipboard ですが、 PowerShell 7で復活しましたね。ただ、公式の Issue によると、PowerShell のクリップボードまわりはテキストのみ扱う方針だそうです(OS に依存しない動作を実現するためのデザインとのこと)。

PowerShell 5以前にあった -Format オプションはファイル形式を指定したコピーなど日常のちょっとした操作で便利だったので、.Net Core 化した PowerShell 7でも似たようなことをしてみようと思います。

ファイルをクリップボードにコピーする

パイプラインで受け取る使い方がメインなので自動変数 $input を使っています。

function Set-ClipboardFile {
    <#
        .EXAMPLE
        ls | Set-ClipboardFile
    #>
    [Windows.Forms.Clipboard]::SetFileDropList($input)
}

※クリップボードに「切り取る」のは以前に 別記事 で紹介しています。

クリップボードのファイルを取得する

function Get-ClipboardFile {
    return $([Windows.Forms.Clipboard]::GetFileDropList() | Get-Item)
}

番外編:クリップボードの画像をファイルに保存する

クリップボード中の画像を取得してファイルに書き出すコマンドも作ってみました。Win+Shift+S でキャプチャした内容を画像ファイルとして保存するときに活躍します。

function Convert-ClipboardImage2File {
    param (
        [string]$basename,
        [switch]$force
    )
    $img = [Windows.Forms.Clipboard]::GetImage()
    if(-not $img) {
        return
    }
    if (-not $basename) {
        $basename = Get-Date -Format yyyyMMddHHmmss
    }
    $fullpath = $pwd.Path | Join-Path -ChildPath ($basename + ".png")
    if (Test-Path $fullpath) {
        if (-not $force) {
            Write-Host ("'{0}{1}' already exists!" -f $basename, $extension) -ForegroundColor Magenta
            return
        }
    }
    $img.save($fullpath)
    Write-Host "save clipboard image as " -NoNewline
    Write-Host ("'{0}{1}'" -f $basename, $extension) -ForegroundColor Cyan
}

ファイル名を指定しない場合はその時点のタイムスタンプで保存するようにしています。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?