2013年11月14日木曜日

URLエンコード、URLデコードをする

関数


# ------------------------------------------------------------------
# 指定した文字コードより、文字列をURLエンコードする
# 関数名:Get-URLEncode
# 引数 :VALUE URLエンコードする文字列
# :ENCODING 文字コード
# 戻り値:URLエンコードした文字列
# ------------------------------------------------------------------
function Get-URLEncode([String]$VALUE, [String]$ENCODING){
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web")
$enc= [System.Text.Encoding]::GetEncoding($ENCODING)
return [System.Web.HttpUtility]::UrlEncode($VALUE,$enc)
}

# ------------------------------------------------------------------
# 指定した文字コードより、文字列をURLデコードする
# 関数名:Get-URLDecode
# 引数 :VALUE URLデコードする文字列
# :ENCODING 文字コード
# 戻り値:URLデコードした文字列
# ------------------------------------------------------------------
function Get-URLDecode([String]$VALUE, [String]$ENCODING){
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web")
$enc= [System.Text.Encoding]::GetEncoding($ENCODING)
return [System.Web.HttpUtility]::UrlDecode($VALUE,$enc)
}

実行例

# 実行
PS > Get-URLEncode -VALUE "あいうえお" -ENCODING "utf-8"
%e3%81%82%e3%81%84%e3%81%86%e3%81%88%e3%81%8a
# 実行
PS > Get-URLDecode-VALUE "%e3%81%82%e3%81%84%e3%81%86%e3%81%88%e3%81%8a" -ENCODING "utf-8"
あいうえお

メモ

文字コードの指定「Encoding.GetEncoding」


2013年11月3日日曜日

ファイル名を置換する

関数


# ------------------------------------------------------------------
# ファイル名を置換する
# 関数名:Replace-FileName
# 引数 :FilePath ファイル名を置換するファイルパス
# :Befor 置換前
# :After 置換後
# 戻り値:なし
# ------------------------------------------------------------------
function Replace-FileName([String]$FilePath, [String]$Befor, [String]$After){
if(Test-Path -LiteralPath $FilePath -PathType Leaf){
$fileInfo = Get-ChildItem -LiteralPath $FilePath
# 置換対象が存在する場合
if($fileInfo.BaseName -match $Befor){
# 置換
$newFileName = ($fileInfo.BaseName -replace $Befor,$After) + $fileInfo.Extension
$newFilePath = Join-Path -Path (Split-Path $FilePath -Parent) -ChildPath $NewFileName
Move-Item -LiteralPath $FilePath -Destination $newFilePath
}
}else{
Write-Host "ファイルが存在しません。ファイル名[ $FilePath ]"
}
}

実行例

$FolderPath = "C:\sample"
$Include = "*.xls"
$Befor = "\["
$After = "【"
Get-ChildItem $FolderPath -Recurse -Include $Include |
ForEach-Object{
  Replace-FileName -FilePath $_.FullName -Befor $Befor -After $After
}