Skip to content

Instantly share code, notes, and snippets.

@t-ubukata
Last active July 1, 2025 10:32
Show Gist options
  • Save t-ubukata/c67dbca30072299e7f1e47af4a9c5b8b to your computer and use it in GitHub Desktop.
Save t-ubukata/c67dbca30072299e7f1e47af4a9c5b8b to your computer and use it in GitHub Desktop.
# Strict mode
Set-StrictMode -Version Latest
# Error action
$ErrorActionPreference = "Stop"
# Script's parent path
$PSScriptRoot
# Sets execution policy bypass.
Set-ExecutionPolicy Bypass
# Runs PowerShell with execution policy.
PowerShell -ExecutionPolicy Bypass
# Version
$PSVersionTable
# A user profile path
$profile
# PSReadLine settings
Import-Module PSReadLine
Set-PSReadlineOption -EditMode Emacs
# Parameter
Param($arg1, $arg2)
## Type
Param([string]$arg1)
## Mandatory
Param([parameter(mandatory)][string]$arg1)
## Array
Param([array]$args)
## Validation
Param([ValidateSet("a", "b", "c")]$arg1)
## Bool
Param([switch]$arg1)
# Writes UTF-8 without BOM.
$utf8withoutBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllLines("foo"), $utf8withoutBom)
# Method
"foo" | % GetType
# Selects by index.
@("foo", "bar") | Select-Object -Index 0
# ArrayList
$al = New-Object System.Collections.ArrayList
# OrderedDictionary
$od = [ordered]{
a = 1
b = 2
c = 3}
# HTTP Request
Invoke-WebRequest "uri"
# XML
$xmlDoc = [xml](Get-Content "foo.xml" -Encoding UTF8)
# JSON
$obj = (Get-Content "path/to/file.json" | ConvertFrom-Json)
$utf8withoutBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllLines("path/to/file.json",(ConvertTo-Json $obj), $utf8withoutBom)
# User environment variable "Path"
$path = [Environment]::GetEnvironmentVariable("Path", "User")
$path += ";path\to\dir"
[Environment]::SetEnvironmentVariable("Path", $path, "User")
# Credential
$securePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential "computerName\userName", $securePassword
# SMB
Get-SmbMapping
New-SmbMapping -LocalPath "Z:" -RemotePath "\\path\to\remote" -UserName "username" -Password "password" -Persistent $true
Remove-SmbMapping -LocalPath "Z:"
# Radix conversion
## dec to bin
[Convert]::ToString(10, 2)
## dec to hex
[Convert]::ToString(10, 16)
## bin to dec
[Convert]::ToString(0b11111111, 10)
## bin to hex
[Convert]::ToString(0b11111111, 16)
## hex to bin
[Convert]::ToString(0xFF, 2)
## hex to dec
[Convert]::ToString(0xFF, 10)
# Gets free disk space.
Get-CimInstance Win32_PerfFormattedData_PerfDisk_LogicalDisk -Credential $cred -ComputerName $computerName | Select-Object -Property Name, PercentFreeSpace
# Remote service names
Get-CimInstance Win32_Service -Credential $cred -ComputerName $computerName | % {$_.Name -match "$name"}
# CSV
## Reads from a file.
$obj = Import-Csv path/to/file.csv -Encoding UTF8
## Reads from a string.
$obj = ConvertFrom-Csv
@'
0,foo
1,bar
'@
## Writes to a string.
ConvertTo-Csv -NoTypeInformation $obj
## Converts to CSV without double quotations and a header line.
$obj | ConvertTo-Csv -NoTypeInformation -Delimiter ',' | Select-Object -Skip 1 | % {$_ -replace '"',''}
# Gets service name, state, start mode, start name.
Get-CimInstance -Class Win32_Service -Property name,state,startmode,startname -Filter 'name="serviceName"'
# Operates Excel with COM object Excel.Application
$xlapp = New-Object -ComObject Excel.Application
$xlapp.Visible = $false
$xlapp.DisplayAlerts = $false
$book = $xlapp.Workbooks.Open("path/to/file")
$sheet = $book.Sheets(1)
$value = $sheet.Range(1, 1).Value()
$sheet.Range(1, 1).Value() = 0
$text = $sheet.Cells.Item(1, 1).Text
$sheet.Cells.Item(1, 1) = "foo"
$book.Save()
$xlapp.Quit()
$xlapp = $null
# IPアドレス各オクテット整数を16進表記文字列に変換する
# 戻り値: 16進表記ドット区切りなしのIPアドレス文字列
function Get-IPAddressHex {
[CmdletBinding()]
Param(
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[int]$IP1decimal, # 10進表記IPアドレス第1オクテット
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[int]$IP2decimal, # 10進表記IPアドレス第2オクテット
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[int]$IP3decimal, # 10進表記IPアドレス第3オクテット
[parameter(Mandatory=$true, ValueFromPipeline=$true)]
[int]$IP4decimal # 10進表記IPアドレス第4オクテット
)
Process {
$IP1hex = $IP1decimal.ToString("X").PadLeft(2, "0")
$IP2hex = $IP2decimal.ToString("X").PadLeft(2, "0")
$IP3hex = $IP3decimal.ToString("X").PadLeft(2, "0")
$IP4hex = $IP4decimal.ToString("X").PadLeft(2, "0")
return $IP1hex + $IP2hex + $IP3hex + $IP4hex
}
}
# 共有アクセス許可テスト
# AccessMaskについては下記参照
# https://docs.microsoft.com/en-us/previous-versions/windows/desktop/secrcw32prov/win32-ace
It "fooの共有アクセス許可 Administratorにフルコントロールが許可されている" {
$setting = Get-CimInstance win32_LogicalShareSecuritySetting -Filter "name='foo'"
$acls = $setting.GetSecurityDescriptor().Descriptor.DACL
$result = ""
foreach($acl in $acls) {
if($acl.Trustee.Name -eq "Administrator") {
switch($acl.AccessMask) {
2032127 {$result = "FullControl"}
1245631 {$result = "Change"}
1179817 {$result = "Read"}
}
}
}
$result | Should -Be "FullControl"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment