Skip to content

Instantly share code, notes, and snippets.

@shiguruikai
Last active May 7, 2026 16:02
Show Gist options
  • Select an option

  • Save shiguruikai/020ca402002d079a8e080d5eb3a80f85 to your computer and use it in GitHub Desktop.

Select an option

Save shiguruikai/020ca402002d079a8e080d5eb3a80f85 to your computer and use it in GitHub Desktop.
自分用のPowerShellプロファイル
function TextEncodingsArgumentCompleter {
[OutputType([System.Management.Automation.CompletionResult])]
param(
[string]$CommandName,
[string]$ParameterName,
[string]$WordToComplete,
[System.Management.Automation.Language.CommandAst]$CommandAst,
[System.Collections.IDictionary]$FakeBoundParameters
)
$ErrorActionPreference = 'Stop'
[System.Text.Encoding]::GetEncodings() `
| Where-Object { $_.Name -like "$wordToComplete*" } `
| Sort-Object Name `
| ForEach-Object {
[System.Management.Automation.CompletionResult]::new(
$_.Name,
$_.Name,
[System.Management.Automation.CompletionResultType]::ParameterValue,
$_.DisplayName)
}
}
function Test-IsAdmin {
[CmdletBinding()]
[OutputType([bool])]
param()
begin {
$ErrorActionPreference = 'Stop'
}
process {
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [System.Security.Principal.WindowsPrincipal]::new($identity)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
return $principal.IsInRole($adminRole)
}
}
function Start-PSAdmin {
[CmdletBinding()]
[OutputType([void])]
param()
begin {
$ErrorActionPreference = 'Stop'
}
process {
Start-Process PowerShell -Verb RunAs -ArgumentList '-NoExit', '-Command', "cd `"$($PWD.Path)`""
}
}
function Get-StringHash {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[string]
$InputObject,
[Parameter(
Position = 1
)]
[ValidateSet('MD5', 'SHA1', 'SHA256', 'SHA384', 'SHA512')]
[string]
$Algorithm = 'SHA256'
)
begin {
$ErrorActionPreference = 'Stop'
switch ($Algorithm) {
'MD5' { $hashAlgorithm = [System.Security.Cryptography.MD5]::Create() }
'SHA1' { $hashAlgorithm = [System.Security.Cryptography.SHA1]::Create() }
'SHA256' { $hashAlgorithm = [System.Security.Cryptography.SHA256]::Create() }
'SHA384' { $hashAlgorithm = [System.Security.Cryptography.SHA384]::Create() }
'SHA512' { $hashAlgorithm = [System.Security.Cryptography.SHA512]::Create() }
default { throw "Unsupported algorithm: $Algorithm" }
}
}
process {
$inputBytes = [System.Text.Encoding]::UTF8.GetBytes($InputObject)
$hashBytes = $hashAlgorithm.ComputeHash($inputBytes)
$hashString = [System.BitConverter]::ToString($hashBytes).Replace("-", "").ToLower()
return $hashString
}
end {
if ($null -ne $hashAlgorithm) {
$hashAlgorithm.Dispose()
}
}
}
function ConvertTo-Base64String {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[System.Object]
$InputObject,
[Parameter()]
[string]
$Encoding = "utf-8"
)
begin {
$ErrorActionPreference = 'Stop'
$enc = [System.Text.Encoding]::GetEncoding($Encoding)
}
process {
[byte[]]$inputBytes = $null
if ($InputObject -is [string]) {
$inputBytes = $enc.GetBytes($InputObject)
}
elseif ($InputObject -is [byte[]]) {
$inputBytes = $InputObject
}
elseif ($InputObject -is [System.IO.FileInfo]) {
$inputBytes = [System.IO.File]::ReadAllBytes($InputObject.FullName)
}
else {
throw "Unsupported input object type: $($InputObject.GetType())"
}
return [System.Convert]::ToBase64String($inputBytes)
}
}
Register-ArgumentCompleter -CommandName ConvertTo-Base64String -ParameterName Encoding -ScriptBlock $Function:TextEncodingsArgumentCompleter
function ConvertFrom-Base64String {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[string]
$InputObject,
[Parameter()]
[string]
$Encoding = 'utf-8'
)
begin {
$ErrorActionPreference = 'Stop'
$enc = [System.Text.Encoding]::GetEncoding($Encoding)
}
process {
$decodedBytes = [System.Convert]::FromBase64String($InputObject)
return $enc.GetString($decodedBytes)
}
}
Register-ArgumentCompleter -CommandName ConvertFrom-Base64String -ParameterName Encoding -ScriptBlock $Function:TextEncodingsArgumentCompleter
function time {
[CmdletBinding()]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName = $true,
Position = 0
)]
[scriptblock]
$ScriptBlock,
[Parameter(
ValueFromPipelineByPropertyName = $true
)]
[string]
$Label
)
process {
$startTime = Get-Date
$result = & $ScriptBlock
$endTime = Get-Date
$exitCode = $LASTEXITCODE
$elapsedTime = New-TimeSpan -Start $startTime -End $endTime
$props = [ordered]@{}
if ($Label) {
$props.Label = $Label
}
$props.StartTime = $startTime
$props.EndTime = $endTime
$props.ElapsedTime = $elapsedTime.ToString('hh\:mm\:ss\.fff')
$props.ExitCode = $exitCode
$props.Result = $result
return [PSCustomObject]$props
}
}
function Get-LineCount {
[CmdletBinding()]
[OutputType([long])]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[string]
$Path
)
begin {
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition @"
using System;
using System.IO;
public static class LineCounter {
public static long CountLines(string path) {
const int maxBufferSize = 1024 * 1024;
long fileSize = new FileInfo(path).Length;
int bufferSize = (int)Math.Max(1, Math.Min(fileSize, maxBufferSize));
byte[] buffer = new byte[bufferSize];
long count = 0;
using (FileStream stream = new FileStream(
path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan)) {
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, bufferSize)) > 0) {
for (int i = 0; i < bytesRead; i++) {
if (buffer[i] == (byte)'\n') count++;
}
}
}
return count;
}
}
"@
}
process {
$p = Convert-Path $Path
$count = [LineCounter]::CountLines($p)
return [PSCustomObject]@{
Path = $p
LineCount = $count
}
}
}
# ------------------------------------------------------------------------------
# プロンプトの設定
# ------------------------------------------------------------------------------
function prompt {
[string]$currentPath = $ExecutionContext.SessionState.Path.CurrentLocation.ProviderPath
# PowerShellと.NETのカレントディレクトリは別々に管理されているため、
# .NETのカレントディレクトリをPowerShellのカレントディレクトリに合わせる。
# これにより、.NETのAPIを使うときに相対パスを指定してもPowerShellとズレないようになる。
if ($ExecutionContext.SessionState.Path.CurrentLocation.Provider.Name -eq 'FileSystem') {
[System.IO.Directory]::SetCurrentDirectory($currentPath)
}
# ホームディレクトリを ~ に省略
if ($currentPath.StartsWith($HOME)) {
$currentPath = "~" + $currentPath.Substring($HOME.Length)
}
# 管理者なら # 一般ユーザーなら $ をプロンプト文字として表示する。
$promptChar = if (Test-IsAdmin) { '#' } else { '$' }
# 現在の時刻を表示する。
$time = (Get-Date).ToString('HH\:mm\:ss')
Write-Host "[$time] " -NoNewline -ForegroundColor DarkGray
# カレントディレクトリを表示する。
Write-Host $currentPath -NoNewline -ForegroundColor Blue
return "`n$($promptChar * ($NestedPromptLevel + 1)) "
}
# ------------------------------------------------------------------------------
# PSReadlineOptionの設定
# ------------------------------------------------------------------------------
# 以下のいずれかに該当するコマンドを履歴に保存させない。
# - 空白文字から始まる
# - exit
Set-PSReadlineOption -AddToHistoryHandler {
param ($Command)
switch -regex ($Command) {
'^\s' { return $false }
'exit' { return $false }
}
return $true
}
# 単語の区切り文字の設定
Set-PSReadLineOption -WordDelimiters (' ・,、;:!?。()[]{}〈〉《》「」『』【】〔〕/\<>|' + (Get-PSReadLineOption).WordDelimiters)
# ------------------------------------------------------------------------------
# ショートカットの設定
# ------------------------------------------------------------------------------
# Alt+r でプロファイルを再読み込みする。
Set-PSReadLineKeyHandler -Chord 'Alt+r' -BriefDescription 'reload $PROFILE' -LongDescription 'reload $PROFILE' -ScriptBlock {
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert(' . $PROFILE')
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
# Alt+` を入力したとき、なぜか@が入力されるのを防止する。
# Alt+` は、英語配列キーボードを日本語環境で使用する際に、IMEの切り替えで使用する。
Set-PSReadLineKeyHandler -Chord 'Alt+@' -BriefDescription 'ignore Alt+@`' -LongDescription 'ignore Alt+@`' -ScriptBlock {}
# Tab で入力候補のメニューを表示する。
Set-PSReadLineKeyHandler -Chord 'Tab' -Function MenuComplete
# ------------------------------------------------------------------------------
# エイリアスの設定
# ------------------------------------------------------------------------------
Set-Alias which where.exe
Set-Alias open explorer.exe
# ------------------------------------------------------------------------------
# エンコーディングの設定
# ------------------------------------------------------------------------------
# 要注意: コンソールのデフォルトエンコーディングをUTF-8に設定する。
$OutputEncoding = [System.Text.Encoding]::UTF8
[System.Console]::InputEncoding = [System.Text.Encoding]::UTF8
[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# 要注意: すべてのコマンドレットのEncodingパラメーターのデフォルト値をutf-8にする。
# 問題が多いので、使用しない。
# $PSDefaultParameterValues['*:Encoding'] = 'utf-8'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment