Last active
October 9, 2024 01:24
-
-
Save AJpon/df3a707871be67df111b9a7c210ee463 to your computer and use it in GitHub Desktop.
私が PowerShell Script を書く際、環境差を吸収するためによく使うおまじない
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[CmdletBinding()] | |
[OutputType()] | |
param() | |
#region PreProcess | |
# おまじない | |
# https://gist.github.com/AJpon/df3a707871be67df111b9a7c210ee463 | |
# このスクリプトで実行したコマンド履歴は | |
# PSReadLineHistory に保存しないようにする | |
$PSReadLineHistorySaveStyle = "Never" | |
# コンソールの書き込み設定を変更 | |
# $VerbosePreference = "Continue" | |
if ($PSBoundParameters['Debug']) { | |
$DebugPreference = "Continue" | |
} | |
$ErrorActionPreference = "Stop" | |
Write-Verbose "PowerShell Version:`n$($PSVersionTable | Format-Table | Out-String)" | |
# $PSScriptRoot は状況によってはスクリプトのルートではないパスを返すため | |
# どのような状況でもスクリプト(もしくはコンパイルしたexeファイル)のルートを取得できる関数を定義 | |
function Get-ScriptRoot { | |
<# | |
.SYNOPSIS | |
Get the script/executable path. | |
.DESCRIPTION | |
Get the script/executable path independant of compiled/not compiled with this function. | |
$PSScriptRoot and $MyInvocation are not available in all scenarios. | |
However, this function will always return the correct path. | |
.OUTPUTS | |
System.String | |
#> | |
[string] $ScriptRoot | |
if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript") { | |
$ScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition | |
} | |
else { | |
$ScriptRoot = Split-Path -Parent -Path ([Environment]::GetCommandLineArgs()[0]) | |
if (!$ScriptRoot) { $ScriptRoot = "." } | |
} | |
# Write-Host "ScriptRoot: $ScriptRoot" | |
return $ScriptRoot | |
} | |
# コンソールの文字コードをUTF-8に変更 | |
#! Windows PowerShell を使用する場合は | |
#! Bom付きUTF-8にしか対応してないので注意 | |
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 | |
#* Optional: スクリプトのルートに移動 | |
# Set-Location Get-ScriptRoot | |
#* Optional: PowerShell Core ではなく、Windows PowerShell で実行することを保証する場合 | |
#region Restart with powershell.exe | |
# pwsh.exe で実行されている場合、Method invocation failed because [System.IO.FileInfo] does not contain a method named 'op_Addition'. | |
# powershell.exe で自分自身を再起動する | |
if ($PSVersionTable.PSVersion.Major -ge 6) { | |
Write-Warning "This script is not compatible with PowerShell Core" | |
Write-Host "Re-launching with powershell.exe" | |
& powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& $($MyInvocation.MyCommand.Path) { $args }" | |
exit $LASTEXITCODE | |
} | |
#endregion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment