PowerShell小僧:スペースを含むファイル名 [コンピューター]
次のコマンドレットの$NewItem1にスペースを含むファイル名(フルパス)を与えるとエラーになります。
$NewItem1 = "C:\aaa\bbb\cc dd.txt"
$ScriptFile1 = $ScriptPath1 + "\nkf_UTF8wBOM1.ps1 -TargetFile1 $NewItem1 -ScriptPath1 $ScriptPath1"
そこで、$NewItem1に含まれるスペースをアンダーバーに変換することでエラーを回避します。
$NewItem1 = "C:\aaa\bbb\cc dd.txt"
$NewItem2 = myFRnSpToUBar1 -TargetFile1 $NewItem1
$ScriptFile1 = $ScriptPath1 + "\nkf_UTF8wBOM1.ps1 -TargetFile1 $NewItem2 -ScriptPath1 $ScriptPath1"
# 関数:ファイル名の空白をアンダーバーに変換
function myFRnSpToUBar1{
param (
[Parameter(Mandatory=$true)]
[String]$TargetFile1 # 対象ファイル
)
# ドットソース演算子
# .{}の中の標準出力は戻り値に含めない
.{
$NewFileName1 = (Get-ChildItem -Path ($TargetFile1)).Name -replace '\s','_'
$ParentPath1 = Split-Path $TargetFile1 -Parent
$NewFilePath1 = $ParentPath1 + "\" + $NewFileName1
Write-Host "`$NewFilePath1=$NewFilePath1"
# ファイル名置換(空白→アンダーバー)
get-childitem $TargetFile1|Rename-Item -NewName { $_.Name -replace '\s','_' }
}>$null
Return $NewFilePath1
}
$NewItem1 = "C:\aaa\bbb\cc dd.txt"
$ScriptFile1 = $ScriptPath1 + "\nkf_UTF8wBOM1.ps1 -TargetFile1 $NewItem1 -ScriptPath1 $ScriptPath1"
そこで、$NewItem1に含まれるスペースをアンダーバーに変換することでエラーを回避します。
$NewItem1 = "C:\aaa\bbb\cc dd.txt"
$NewItem2 = myFRnSpToUBar1 -TargetFile1 $NewItem1
$ScriptFile1 = $ScriptPath1 + "\nkf_UTF8wBOM1.ps1 -TargetFile1 $NewItem2 -ScriptPath1 $ScriptPath1"
# 関数:ファイル名の空白をアンダーバーに変換
function myFRnSpToUBar1{
param (
[Parameter(Mandatory=$true)]
[String]$TargetFile1 # 対象ファイル
)
# ドットソース演算子
# .{}の中の標準出力は戻り値に含めない
.{
$NewFileName1 = (Get-ChildItem -Path ($TargetFile1)).Name -replace '\s','_'
$ParentPath1 = Split-Path $TargetFile1 -Parent
$NewFilePath1 = $ParentPath1 + "\" + $NewFileName1
Write-Host "`$NewFilePath1=$NewFilePath1"
# ファイル名置換(空白→アンダーバー)
get-childitem $TargetFile1|Rename-Item -NewName { $_.Name -replace '\s','_' }
}>$null
Return $NewFilePath1
}
ヤバイぜ! ありがとうございます(^_0)ノ
by cheese999 (2021-11-02 17:31)