Skip to content

Instantly share code, notes, and snippets.

@shiguruikai
Last active March 21, 2023 23:16
Show Gist options
  • Save shiguruikai/020ca402002d079a8e080d5eb3a80f85 to your computer and use it in GitHub Desktop.
Save shiguruikai/020ca402002d079a8e080d5eb3a80f85 to your computer and use it in GitHub Desktop.
自分用のPowerShellプロファイル
# beep音を無効化
Set-PSReadlineOption -BellStyle None
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'
$encodings = [System.Text.Encoding]::GetEncodings()
$results = $encodings | Where-Object { $_.Name -like "$wordToComplete*" } | Sort-Object Name | ForEach-Object {
[System.Management.Automation.CompletionResult]::new(
$_.Name,
$_.Name,
[System.Management.Automation.CompletionResultType]::ParameterValue,
$_.DisplayName)
}
return $results
}
Register-ArgumentCompleter -CommandName ConvertTo-Base64 -ParameterName Encoding -ScriptBlock $Function:TextEncodingsArgumentCompleter
Register-ArgumentCompleter -CommandName ConvertFrom-Base64 -ParameterName Encoding -ScriptBlock $Function:TextEncodingsArgumentCompleter
function Get-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'
$hashAlgorithm = [System.Security.Cryptography.HashAlgorithm]::Create($Algorithm)
}
process {
$inputBytes = [System.Text.Encoding]::UTF8.GetBytes($InputObject)
$hashBytes = $hashAlgorithm.ComputeHash($inputBytes)
$hashString = ($hashBytes | ForEach-Object { $_.ToString('x2') }) -join ''
return $hashString
}
end {
if ($null -ne $hashAlgorithm) {
$hashAlgorithm.Dispose()
}
}
}
function ConvertTo-Base64 {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[string]
$InputObject,
[Parameter()]
[string]
$Encoding = 'utf-8'
)
begin {
$ErrorActionPreference = 'Stop'
}
process {
$inputBytes = [System.Text.Encoding]::GetEncoding($Encoding).GetBytes($InputObject)
return [System.Convert]::ToBase64String($inputBytes)
}
}
function ConvertFrom-Base64 {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[string]
$InputObject,
[Parameter()]
[string]
$Encoding = 'utf-8'
)
begin {
$ErrorActionPreference = 'Stop'
}
process {
$decodedBytes = [System.Convert]::FromBase64String($InputObject)
return [System.Text.Encoding]::GetEncoding($Encoding).GetString($decodedBytes)
}
}
# BUG: 標準エラー出力がされない。
function time {
[CmdletBinding()]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[scriptblock]
$Expression
)
begin {
$ErrorActionPreference = 'Stop'
$startTime = Get-Date
}
process {
$Expression.Invoke()
}
end {
$elapsedTime = New-TimeSpan $startTime (Get-Date)
Write-Host "`nElapsed: $($elapsedTime.ToString('hh\:mm\:ss\.fff'))"
}
}
if (Get-Command jshell -ErrorAction SilentlyContinue) {
# 巨大なファイルの行数を取得するときに使う。
function Get-LineCount {
[CmdletBinding()]
param (
[Parameter(
Mandatory,
ValueFromPipeline,
Position = 0
)]
[string]
$Path
)
begin {
$ErrorActionPreference = 'Stop'
$jshSrc = @"
final var filePath = Paths.get(System.getProperty("file"));
long clamp(long value, long min, long max) {
return Math.max(min, Math.min(max, value));
}
try (var channel = Files.newByteChannel(filePath, StandardOpenOption.READ)) {
final var bufferSize = (int) clamp(Files.size(filePath), 1, 1024 * 1024);
final var buf = java.nio.ByteBuffer.allocateDirect(bufferSize);
var result = 0L;
while (channel.read(buf) != -1) {
buf.flip();
while (buf.hasRemaining())
if (buf.get() == '\n')
result++;
buf.clear();
}
System.out.println(result);
}
/exit
"@
}
process {
$file = (Get-Item $Path).FullName -replace '\\', '/'
$jshSrc | jshell -R "-Dfile=$file" -
}
}
}
# プロンプトの設定
function prompt {
# 可能であれば、.NETのカレントディレクトリをPowerShellのカレントディレクトリにします。
if ($PWD.Provider.Name -eq 'FileSystem') {
[System.IO.Directory]::SetCurrentDirectory($PWD.ProviderPath)
}
$promptChar = '$'
if (Get-IsAdmin) {
$promptChar = '#'
}
return "PS $($ExecutionContext.SessionState.Path.CurrentLocation.ProviderPath)`n$($promptChar * ($nNestedPromptLevel + 1)) ";
}
Set-Alias which where.exe
Set-Alias open explorer.exe
# 下記のコマンドを履歴に保存しない。
# ・空白文字から始まる
# ・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+` を入力したとき、なぜか@が入力されるのを防止する。
Set-PSReadLineKeyHandler -Chord 'Alt+@' -BriefDescription 'ignore Alt+@`' -LongDescription 'ignore Alt+@`' -ScriptBlock {}
# Tab で入力候補のメニューを表示する。(Ctrl+Spacebarと同じ)
Set-PSReadLineKeyHandler -Chord 'Tab' -Function MenuComplete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment