PowerShellでImageMagickなどの外部コマンドに渡す“出力先パス”だけ作りたい場合があります。System.IO.Pathを使えば比較的簡単な文字列操作ですが、あらかじめ関数として作成してみます。
TL;DR(コピペ用)
$PROFILE
に以下を追記して使います。
# --- suffix: 拡張子の直前に付ける ---
function suffix {
param([Parameter(Mandatory)][string]$Path, [string]$Suffix = '_suffix')
$dir = Split-Path -LiteralPath $Path
$name = [IO.Path]::GetFileName($Path)
$ext = [IO.Path]::GetExtension($name) # 例: a.tar.gz -> .gz
$stem = if ($ext) { $name.Substring(0, $name.Length - $ext.Length) } else { $name }
$new = "$stem$Suffix$ext" # 例: a.tar_resize.gz
if ($dir) { Join-Path $dir $new } else { $new }
}
# --- prefix: 先頭に付ける ---
function prefix {
param([Parameter(Mandatory)][string]$Path, [string]$Prefix = 'prefix_')
$dir = Split-Path -LiteralPath $Path
$name = [IO.Path]::GetFileName($Path)
$new = "$Prefix$name"
if ($dir) { Join-Path $dir $new } else { $new }
}
Set-Alias suf suffix
Set-Alias pre prefix
プロファイルの開き方と反映
notepad $PROFILE # ない場合は保存時に作成
. $PROFILE # 変更を反映(ドットソース)
使い方
suffix C:\img\a.tar.gz _50
# => C:\img\a.tar_50.gz
prefix C:\img\p.png th_
# => C:\img\th_p.png
外部ツールと組み合わせ(例:ImageMagick で 50% 縮小して新パスへ出力)
$p = '.\image.png' magick $p -filter Lanczos -resize 50% -strip (suffix $p "_resize")
コメント