バッチファイルを管理者権限で実行する（ネットワークドライブ対応版）２０２３リメイク版

バッチファイルを管理者権限へ昇格して実行します。
2021年に作成した「[バッチファイルを管理者権限で実行する（ネットワークドライブ対応版）](https://qiita.com/hatachu/items/2918cf20311cabde6c5d "バッチファイルを管理者権限で実行する（ネットワークドライブ対応版）")」を、リメイクしました。
Windows 8.1, 10, 11 で動作します。
文字コードは ANSI 形式で保存してください。

```AdminAccess_BFW2023.bat
@echo off
for /f "usebackq tokens=2 delims=:" %%A in (`chcp`) do (set "ACTIVE_CP=%%A")
chcp 932 >nul
setlocal

set /a Arg_R=0
set /a Arg_S=0
for %%a in (%*) do (
	if /i %%a==/R (set /a Arg_R=1)
	if /i %%a==/S (set /a Arg_S=1)
)

:checkMandatoryLevel
	set "BatchArgs=%*"
	call :checkMandatoryLevelandElevate
	if %errorlevel% equ 0 (
		set "gtLBL=admins"
	) else (
		set "gtLBL=exit1"
	)
	goto %gtLBL%

:admins
	echo 管理者権限でアクセスしました。(Accessed with administrator privileges.)
	dir "%~f0"
	call :isnwpath
	if /i "%isnwpath_result%"=="True" (
		powershell -NoProfile -Command "Get-SmbConnection;"
	)
	
	if %Arg_S% equ 0 pause
	
	goto exit1
	
	:isnwpath
		set "FP=%~f0"
		set PS_IsNwPath=^
			$FP = $env:FP;^
			if (([System.Uri]$FP).IsUnc) {^
				$ReturnValue = $true;^
			} else {^
				$FP_Qualifier = Split-Path -Path $FP -Qualifier 2^> $null;^
				if ($FP_Qualifier -ne $null) {^
					$FP_ProviderName = (Get-WMIObject -Class Win32_MappedLogicalDisk -Filter \"DeviceID ^= '$FP_Qualifier'\").ProviderName;^
					if ($FP_ProviderName -ne $null) {^
						$FP_NoQualifier = Split-Path -Path $FP -NoQualifier;^
						$FP_UNCPath = Join-Path -Path $FP_ProviderName -ChildPath $FP_NoQualifier;^
					}^
				}^
				if ($FP_UNCPath -eq $null) {^
					$ReturnValue = $false;^
				} else {^
					$ReturnValue = $true;^
				}^
			}^
			return $ReturnValue;
		
		for /f "usebackq tokens=*" %%A in (`powershell -NoProfile -Command "%PS_IsNwPath%"`) do (set "isnwpath_result=%%A")
	exit /b

:checkMandatoryLevelandElevate
	set "FP=%~f0"
	set PSCommand=^
		if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {^
			Write-Host 'このファイルは管理者権限での実行が必要です [プロセスの昇格が必要]';^
			$returnValue = 2;^
			if ($env:Arg_R -eq 1) {^
				$returnValue = 3;^
			} else {^
				$FP_Qualifier = Split-Path -Path $env:FP -Qualifier 2^> $null;^
				if ($null -ne $FP_Qualifier) {^
					$FP_ProviderName = (Get-WMIObject -Class Win32_MappedLogicalDisk -Filter "DeviceID = '$FP_Qualifier'").ProviderName;^
					if ($null -ne $FP_ProviderName) {^
						$FP_NoQualifier = Split-Path -Path $env:FP -NoQualifier;^
						$FP_UNCPath = Join-Path -Path $FP_ProviderName -ChildPath $FP_NoQualifier;^
					}^
				}^
				if ($null -eq $FP_UNCPath) {^
					$FP = $env:FP;^
				} else {^
					$FP = $FP_UNCPath;^
				}^
				$FP_Base64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($FP));^
				if ($null -ne $env:BatchArgs) {^
					$BatchArgs_Base64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($env:BatchArgs));^
				}^
				$PS_RunAs_Args = '-NoProfile -Command ';^
				$PS_RunAs_Args += '$FP_Base64 = ' + "'$FP_Base64';";^
				$PS_RunAs_Args += '$BatchArgs_Base64 = ' + "'$BatchArgs_Base64';";^
				$PS_RunAs_Args += '$FP = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($FP_Base64));';^
				$PS_RunAs_Args += 'if ($null -ne $BatchArgs_Base64) {';^
				$PS_RunAs_Args += '	$BatchArgs = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($BatchArgs_Base64));';^
				$PS_RunAs_Args += '}';^
				$PS_RunAs_Args += '$Arg_S = ' + "$env:Arg_S;";^
				$PS_RunAs_Args += 'if (($Arg_S -eq 0) -and [bool]([System.Uri]$FP).IsUnc -and !(Test-Path -LiteralPath $FP -PathType Leaf)) {';^
				$PS_RunAs_Args += '	$cred = Get-Credential -Message "次にアクセスするための資格情報を入力してください:` $FP";';^
				$PS_RunAs_Args += '	New-PSDrive -Name TargetUNCPath -PSProvider FileSystem -Root (Split-Path -Path $FP -Parent) -Credential $cred;';^
				$PS_RunAs_Args += '}';^
				$PS_RunAs_Args += '$ArguList = ''"/s /c """"""'' + $FP + ''"""" '' + $BatchArgs + '' /R"""'';';^
				$PS_RunAs_Args += 'Start-Process -FilePath ' + "'$env:ComSpec'" + ' -ArgumentList $ArguList;';^
				Start-Process -WindowStyle Minimized -Verb RunAs -FilePath powershell -ArgumentList $PS_RunAs_Args;^
			}^
		} else {^
			$returnValue = 0;^
		}^
		exit $returnValue
	
	powershell -NoProfile -Command "Invoke-Expression -Command $env:PSCommand;"
	
exit /b

:exit1
	chcp %ACTIVE_CP% >nul

```


<details><summary>English message version</summary>

Please save the character code in UTF-8 format.

```AdminAccess_BFW2023_UTF8.bat
@echo off
for /f "usebackq tokens=2 delims=:" %%A in (`chcp`) do (set "ACTIVE_CP=%%A")
chcp 65001 >nul
setlocal

set /a Arg_R=0
set /a Arg_S=0
for %%a in (%*) do (
	if /i %%a==/R (set /a Arg_R=1)
	if /i %%a==/S (set /a Arg_S=1)
)

:checkMandatoryLevel
	set "BatchArgs=%*"
	call :checkMandatoryLevelandElevate
	if %errorlevel% equ 0 (
		set "gtLBL=admins"
	) else (
		set "gtLBL=exit1"
	)
	goto %gtLBL%

:admins
	echo (Accessed with administrator privileges.)
	dir "%~f0"
	call :isnwpath
	if /i "%isnwpath_result%"=="True" (
		powershell -NoProfile -Command "Get-SmbConnection;"
	)
	
	if %Arg_S% equ 0 pause
	
	goto exit1
	
	:isnwpath
		set "FP=%~f0"
		set PS_IsNwPath=^
			$FP = $env:FP;^
			if (([System.Uri]$FP).IsUnc) {^
				$ReturnValue = $true;^
			} else {^
				$FP_Qualifier = Split-Path -Path $FP -Qualifier 2^> $null;^
				if ($FP_Qualifier -ne $null) {^
					$FP_ProviderName = (Get-WMIObject -Class Win32_MappedLogicalDisk -Filter \"DeviceID ^= '$FP_Qualifier'\").ProviderName;^
					if ($FP_ProviderName -ne $null) {^
						$FP_NoQualifier = Split-Path -Path $FP -NoQualifier;^
						$FP_UNCPath = Join-Path -Path $FP_ProviderName -ChildPath $FP_NoQualifier;^
					}^
				}^
				if ($FP_UNCPath -eq $null) {^
					$ReturnValue = $false;^
				} else {^
					$ReturnValue = $true;^
				}^
			}^
			return $ReturnValue;
		
		for /f "usebackq tokens=*" %%A in (`powershell -NoProfile -Command "%PS_IsNwPath%"`) do (set "isnwpath_result=%%A")
	exit /b

:checkMandatoryLevelandElevate
	set "FP=%~f0"
	set PSCommand=^
		if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {^
			Write-Host 'Administrator privileges are required to run this file. [Process requires privileges]';^
			$returnValue = 2;^
			if ($env:Arg_R -eq 1) {^
				$returnValue = 3;^
			} else {^
				$FP_Qualifier = Split-Path -Path $env:FP -Qualifier 2^> $null;^
				if ($null -ne $FP_Qualifier) {^
					$FP_ProviderName = (Get-WMIObject -Class Win32_MappedLogicalDisk -Filter "DeviceID = '$FP_Qualifier'").ProviderName;^
					if ($null -ne $FP_ProviderName) {^
						$FP_NoQualifier = Split-Path -Path $env:FP -NoQualifier;^
						$FP_UNCPath = Join-Path -Path $FP_ProviderName -ChildPath $FP_NoQualifier;^
					}^
				}^
				if ($null -eq $FP_UNCPath) {^
					$FP = $env:FP;^
				} else {^
					$FP = $FP_UNCPath;^
				}^
				$FP_Base64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($FP));^
				if ($null -ne $env:BatchArgs) {^
					$BatchArgs_Base64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($env:BatchArgs));^
				}^
				$PS_RunAs_Args = '-NoProfile -Command ';^
				$PS_RunAs_Args += '$FP_Base64 = ' + "'$FP_Base64';";^
				$PS_RunAs_Args += '$BatchArgs_Base64 = ' + "'$BatchArgs_Base64';";^
				$PS_RunAs_Args += '$FP = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($FP_Base64));';^
				$PS_RunAs_Args += 'if ($null -ne $BatchArgs_Base64) {';^
				$PS_RunAs_Args += '	$BatchArgs = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($BatchArgs_Base64));';^
				$PS_RunAs_Args += '}';^
				$PS_RunAs_Args += '$Arg_S = ' + "$env:Arg_S;";^
				$PS_RunAs_Args += 'if (($Arg_S -eq 0) -and [bool]([System.Uri]$FP).IsUnc -and !(Test-Path -LiteralPath $FP -PathType Leaf)) {';^
				$PS_RunAs_Args += '	$cred = Get-Credential -Message "Enter` your` credentials` to` access` to:` $FP";';^
				$PS_RunAs_Args += '	New-PSDrive -Name TargetUNCPath -PSProvider FileSystem -Root (Split-Path -Path $FP -Parent) -Credential $cred;';^
				$PS_RunAs_Args += '}';^
				$PS_RunAs_Args += '$ArguList = ''"/s /c """"""'' + $FP + ''"""" '' + $BatchArgs + '' /R"""'';';^
				$PS_RunAs_Args += 'Start-Process -FilePath ' + "'$env:ComSpec'" + ' -ArgumentList $ArguList;';^
				Start-Process -WindowStyle Minimized -Verb RunAs -FilePath powershell -ArgumentList $PS_RunAs_Args;^
			}^
		} else {^
			$returnValue = 0;^
		}^
		exit $returnValue
	
	powershell -NoProfile -Command "Invoke-Expression -Command $env:PSCommand;"
	
exit /b

:exit1
	chcp %ACTIVE_CP% >nul

```
</details>


# 参考
* https://qiita.com/jTakasuRyuji/items/e7bd576ed57969b2d06e
* https://qiita.com/annatortoise/items/9b3835c94a22592daaa1
* https://ss64.com/nt/syntax.html