🌟

個人的に便利な何か。

に公開

パスを追加するスクリプト

特に、精査してないですがすでにパスがある場合には上書きしないみたい。
個人的には右クリックで適当に環境変数追加できれば満足なので、パス追加が動くことしか検証してないです。便利ですね。

# add_to_path.ps1
# ChatGPT に作らせました。すごいね。

# Check if the script is running as Administrator
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "Administrator privileges are required."
    exit 0
}

# Get the full path of the current working directory
$cwd = (Get-Location).ProviderPath

# Get the current system PATH (Machine scope)
$machinePath = [Environment]::GetEnvironmentVariable("Path", "Machine")

if ([string]::IsNullOrEmpty($machinePath)) {
    $machinePath = ""
}

# Split PATH into individual entries for comparison
$parts = $machinePath -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne "" }

# Check if the current directory is already included
if ($parts -contains $cwd) {
    Write-Host "The current directory is already included in the System PATH:"
    Write-Host "  $cwd"
    exit 0
}

# Prepare the new PATH string
if ($machinePath.EndsWith(";")) {
    $newPath = $machinePath + $cwd
} elseif ($machinePath -eq "") {
    $newPath = $cwd
} else {
    $newPath = $machinePath + ";" + $cwd
}

# Update the System PATH variable
[Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")

# Broadcast a WM_SETTINGCHANGE message to notify the system and other apps
$code = @"
using System;
using System.Runtime.InteropServices;
public class NativeMethods {
    [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
    public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
}
"@
Add-Type $code

$HWND_BROADCAST = [IntPtr]0xffff
$WM_SETTINGCHANGE = 0x001A
$SMTO_ABORTIFHUNG = 0x0002
[UIntPtr]$result = [UIntPtr]::Zero
[NativeMethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, "Environment", $SMTO_ABORTIFHUNG, 5000, [ref]$result) | Out-Null

# Confirm success
Write-Host "Successfully added the current directory to the System PATH:"
Write-Host "  $cwd"
Write-Host ""
Write-Host "Current System PATH entries (partial listing):"
[Environment]::GetEnvironmentVariable("Path", "Machine") -split ";" | ForEach-Object { Write-Host "- $_" }

Discussion