0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

よく使う処理

Last updated at Posted at 2025-05-21

ログ出力用関数

function Write-Log{
    param(
        [Parameter(HelpMessage="出力場所(1:プロンプトとログファイル, 2:ログファイル, それ以外:プロンプト)")]
            $writePlace,
        [Parameter(HelpMessage="ログファイルのパス")]
            $logFilePath,
        [Parameter(HelpMessage="出力ログのメッセージレベル(1:ERROR, 2:WARNING, 3:DEBUG, それ以外:INFO)")]
            [int]$msgLv = 0,
        [Parameter(Mandatory=$true, HelpMessage="出力ログ内容")]
            $msg
    )

    if(-not [string]::IsNullOrEmpty($msg)){
        #出力場所を制御
        switch($writePlace){
                  1 { $prompt = $true;  $logFile = $true  }
                  2 { $prompt = $false; $logFile = $true  }
            default { $prompt = $true;  $logFile = $false }
        }
    
        #メッセージレベルの実価を取得
        switch($msgLv){
                  1 { $msgLvStr = "ERROR"   }
                  2 { $msgLvStr = "WARNING" }
                  3 { $msgLvStr = "DEBUG"   }
            default { $msgLvStr = "INFO"    }
        }
        #出力するメッセージを生成
        $timeStamp = Get-Date -Format "yyyy/MM/dd HH:mm:ss:ff"
        $logMsg = "[$($timeStamp)]【$($msgLvStr)$($msg)"
    
        #ログ出力を実施
        if($prompt)  { Write-Host "$logMsg" }
        if($logFile) {
            try{
                Add-Content -Path $logFilePath -Value "$($logMsg)" -ErrorAction Stop
            }catch{
                Write-Error "ログファイルへの書き込みに失敗しました:$($_.Exception.Message)"
            }
        }
    }
}

ユーザーによる日付確認用関数

function dateUserConfirmed{
    $returnValue = Get-Date
    $inputFormats = @("yyyyMMdd", "yyyy/MM/dd", "yyyy-MM-dd")

    while($true){
        $ynAnswer = Read-Host "日付は $($returnValue.ToString("yyyy/M/d")) でよろしいですか?(Y/N)"
        switch($ynAnswer.Trim().ToUpper()){
            "Y"{
                return $returnValue
            }
            "N"{
                $culture = [System.Globalization.CultureInfo]::InvariantCulture
                $style = [System.Globalization.DateTimeStyles]::None
                $parsedDate = $null
                while($true){
                    $input = Read-Host "希望する日付を、$($inputFormats -join "・")いずれかの形式で入力してください。"
                    if([DateTime]::TryParseExact($input, $inputFormats, $culture, $style, [ref]$parsedDate)){
                        $returnValue = $parsedDate
                        return $returnValue
                    }else{
                        Write-Host "入力形式が異なるか、無効な日付です。`n"
                    }
                }
            }
            default{
                Write-Host "YかNで回答してください。"
            }
        }
    }
}

ユーザーによる日付確認用関数(PowerShell 2.0 + .NET 2.0)

function dateUserConfirmed{
    $isOutestLoopExit = $false
    $returnValue = Get-Date
    $format = "yyyyMMdd"

   while(-not $isOutestLoopExit){
        $ynAnswer = Read-Host "日付は $($returnValue.ToString("yyyy/M/d")) でよろしいですか?(Y/N)"
        switch($ynAnswer.Trim().ToUpper()){
            "Y"{
                 $isOutestLoopExit = $true
            }
            "N"{
                $culture = [System.Globalization.CultureInfo]::InvariantCulture
                while($true){
                    $input = Read-Host "希望する日付を、$($format)の形式で入力してください。"
                    try{
                       $parsedDate = [DateTime]::ParseExact($input, $format, $culture)
                    }catch{
                        Write-Host "入力形式が異なるか、無効な日付です。`n"
                        continue
                    }
                    $returnValue = $parsedDate
                    break
                }
            }
            default{
                Write-Host "YかNで回答してください。"
            }
        }
    }

    return $returnValue
}

ディレクトリ存在確認用関数(存在しなければ作成する)

function isUSeableDir{
    param(
        [Parameter(Mandatory=$true, HelpMessage="ディレクトリのパス")]
        $dirPath
    )
    Write-Host "ディレクトリパスの存在を確認します。【$($dirPath)】"
    if(Test-Path $dirPath){
        if(-not (Test-Path $dirPath -PathType Container)){
            Write-Error "パスは存在していますが、ディレクトリではありません。"
            return $false
        }
        Write-Host "パスは存在しています。"
        return $true
    }else{
        try{
            [System.IO.Directory]::CreateDirectory($dirPath) | Out-Null
        }catch{
            Write-Error "ディレクトリの作成に失敗しました。 … $($_.Exception.Message)"
            return $false
        }
        Write-Host "ディレクトリの作成に成功しました。"
        return $true
    }
}

ワークブックの上書き権限確認関数

function isWbUpdatable{
    param(
        [Parameter(Mandatory=$true)]
        [__ComObject]$wb
    )
    #0.渡された引数がWorkbookオブジェクトかどうか
    try{
        $wb.FullName | Out-Null
        $wb.ReadOnly | Out-Null
        $wb.Saved | Out-Null
        $wb.Worksheets | Out-Null
    }catch{
        return $false
    }
    #1.読み取り専用として開かれているかどうか
    if($wb.ReadOnly){ return $false }
    #2.読み取り専用属性を持っていないかどうか
    $filePath = $wb.FullName
    $file = Get-Item -LiteralPath $filePath
    if($file.Attributes -band [System.IO.FileAttributes]::ReadOnly){
        return $false
    }
    #3.書き込み権限があるかどうか
    try{
        $stream = [System.IO.File]::Open($filePath, 'Open', 'ReadWrite', 'None')
        $stream.Close()
        return $true
    }catch{
        return $false
    }
}

バルーンチップ通知関数

function showNotify{
    param(
        [Parameter(Mandatory=$true)][string]$msg,
        [string]$title = "通知",
        [ValidateSet("Info", "Warning", "Error", "None")]
        [string]$iconType = "Info"
    )
    if(-not ([System.Windows.Forms.Form] -as [Type])) { Add-Type -AssemblyName System.Windows.Forms }
    $notify = New-Object System.Windows.Forms.NotifyIcon
    switch($iconType){
        "Info"  { $notify.Icon = [System.Drawing.SystemIcons]::Information }
        "None"  { $notify.Icon = [System.Drawing.SystemIcons]::Application }
        default { $notify.Icon = [System.Drawing.SystemIcons]::$iconType }
    }
    $notify.BalloonTipIcon = $iconType
    $notify.BalloonTipText = $msg
    $notify.BalloonTipTitle = $title
    $notify.Visible = $true
    $notify.ShowBalloonTip(3000)
    Start-Sleep -Milliseconds 3500
    $notify.Dispose()
}

ショートカット(リンクファイル)作成関数

function makeShortcut{
    param(
        [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$locatePath,
        [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$fileName,
        [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string]$targetPath
    )
    #ショートカット配置先が存在しない場合は作成
    if(-not (Test-Path $locatePath)){
        try{
            [System.IO.Directory]::CreateDirectory($locatePath) | Out-Null
            Write-Host "ショートカット配置先の作成に成功しました。【$($locatePath)】"
        }catch{
            Write-Error "ショートカット配置先の作成に失敗しました。【$($locatePath)】"
        }
    }
    
    #ファイル名に拡張子がない場合は追加
    if(-not ($fileName.ToLower().EndsWith(".lnk"))){ $fileName += ".lnk" }
    
    #ショートカット作成
    $shortcutFullPath = Join-Path -Path $locatePath -ChildPath $fileName
    if(Test-Path $shortcutFullPath){
        $whileBreak = $false
        while(-not $whileBreak){
            $ynAnswer = Read-Host "作成しようとしているショートカットは既存です。上書きしますか?(Y/N)"
            switch($ynAnswer.ToUpper()){
                "Y"{
                    $whileBreak = $true
                }
                "N"{
                    Write-Host "ショートカット作成を取りやめました。"
                    return
                }
                default{
                    Write-Host "YかNを入力してください。"
                }
            }
        }
    }
    try{
        $wsShell = New-Object -ComObject WScript.Shell
        $shortcut = $wsShell.CreateShortCut($shortcutFullPath)
        $shortcut.TargetPath = $targetPath
        $shortcut.Save()
        Write-Host "ショートカット作成に成功しました。【配置場所:$($shortcutFullPath)】【リンク先:$($targetPath)】"
    }catch{
        Write-Error "ショートカット作成に失敗しました。【配置場所:$($shortcutFullPath)】【リンク先:$($targetPath)】 … $($_.Exception.Message)"
    }finally{
        #ComObject解放
        foreach($comObj in @($shortcut, $wsShell)){
            if($comObj -ne $null){
                [System.Runtime.InteropServices.Marshal]::ReleaseComObject($comObj) | Out-Null
            }
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?