【PowerShell】New-Itemはワイルドカード文字を含むハードリンクを作成できない場合がある
環境:
Windows PowerShell 5.1
PowerShell Core 7.4.0
PowerShellでハードリンクを作成するにはNew-Itemを使いますが、このコマンドレットの-Valueパラメーターはワイルドカード文字を解釈します。そのため、ワイルドカード文字をエスケープする必要がありますが、末端以外のフォルダー名にワイルドカード文字が含まれているとエスケープしてもエラーが発生します。
いくつか例を挙げてみます。
まずはファイル名にワイルドカード文字が含まれている場合ですが、これは2回エスケープすればうまくいきます。
#これはうまくいく $hlPath = "D:\Test\hl.txt" $filePath = [WildcardPattern]::Escape([WildcardPattern]::Escape("D:\Test\Dir 1\Dir 2\File [1].txt")) New-Item -ItemType HardLink -Path $hlPath -Value $filePath
末端のフォルダー名にワイルドカード文字が含まれていてもうまくいきます。
#これもうまくいく $hlPath = "D:\Test\hl.txt" $filePath = [WildcardPattern]::Escape([WildcardPattern]::Escape("D:\Test\Dir 1\Dir [2]\File 1.txt")) New-Item -ItemType HardLink -Path $hlPath -Value $filePath
ですが、末端以外のフォルダー名にワイルドカード文字が含まれているとエラーになります。
#これはエラーになる。 $hlPath = "D:\Test\hl.txt" $filePath = [WildcardPattern]::Escape([WildcardPattern]::Escape("D:\Test\Dir [1]\Dir 2\File 1.txt")) New-Item -ItemType HardLink -Path $hlPath -Value $filePath #>>Cannot find path 'D:\Test\Dir ``[1``]\Dir 2\File 1.txt' because it does not exist.
エスケープしなくてもエラーになります。
#これもエラーになる。 $hlPath = "D:\Test\hl.txt" $filePath = "D:\Test\Dir [1]\Dir 2\File 1.txt" New-Item -ItemType HardLink -Path $hlPath -Value $filePath #>>Cannot find path 'D:\Test\Dir [1]\Dir 2\File 1.txt' because it does not exist.
コマンドレットによっては、ワイルドカード文字を解釈するパラメーターと解釈しないパラメーターが用意されていますが (Copy-Itemの-Pathと-LiteralPathなど)、New-Itemの-Valueにはワイルドカード文字を解釈しないパラメーター用意されていないようです。
そのため、ワイルドカード文字を含むハードリンクを作成する場合はmklinkコマンドを使う必要があります。
$hlPath = "D:\Test\hl.txt" $filePath = "D:\Test\Dir [1]\Dir 2\File 1.txt" cmd /c "mklink" /h $hlPath $filePath