SSブログ

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
}
ヤバイぜ!(10)  コメント(1) 
共通テーマ:パソコン・インターネット

ヤバイぜ! 10

コメント 1

cheese999

ヤバイぜ! ありがとうございます(^_0)ノ
by cheese999 (2021-11-02 17:31) 

コメントを書く

お名前:[必須]
URL:
コメント:
画像認証:
下の画像に表示されている文字(英大文字の「オー」、英小文字の「ユー」、アラビア数字の「ハチ」、アラビア数字の「イチ」、アラビア数字の「ニ」)を入力してください。

Facebook コメント

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。