PowerShellの実行ポリシーを変更するバッチファイル

2021/06/25に公開約1,000字

Windows PowerShellでもPowerShell Core系でも動作するハズです。

@echo off
chcp 65001 > nul
setlocal ENABLEDELAYEDEXPANSION

rem Detect PowerShell
set POWERSHELL=
where.exe /r "%SystemRoot%\system32" "powershell.exe" > "%WORKING_DIR%\PowerShell-FilePath.txt" 2>nul
if %ERRORLEVEL% equ 0 (
	rem set POWERSHELL=powershell.exe
	for /f "usebackq delims=" %%a in ("%WORKING_DIR%\PowerShell-FilePath.txt") do (
		set POWERSHELL=%%a
	)
)
del "%WORKING_DIR%\PowerShell-FilePath.txt"
where.exe /r "%PROGRAMFILES%" "pwsh.exe" > "%WORKING_DIR%\Pwsh-FilePath.txt" 2>nul
if %ERRORLEVEL% equ 0 (
	rem set POWERSHELL=pwsh.exe
	for /f "usebackq delims=" %%a in ("%WORKING_DIR%\Pwsh-FilePath.txt") do (
		set POWERSHELL=%%a
	)
)
del "%WORKING_DIR%\Pwsh-FilePath.txt"
if not defined POWERSHELL (
	echo PowerShell is not installed.
	exit /b 1
)
echo PowerShell: %POWERSHELL%

call "%POWERSHELL%" -Command "Set-ExecutionPolicy -Scope CurrentUser RemoteSigned"
rem call "%POWERSHELL%" -Command "Get-ExecutionPolicy -List"

endlocal
exit /b 0

Discussion

ログインするとコメントできます