0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「非管理者として実行したときに管理者として再実行」 & 「batファイルの中にPowerShellスクリプトを埋め込む」を両方実現する

Last updated at Posted at 2024-05-20
run-as-admin-powershell.bat
@SETLOCAL&SETLOCAL ENABLEDELAYEDEXPANSION&(chcp 65001>NUL)&PUSHD "%~dp0"&(SET SCRIPT_PATH=%~f0)&(SET SCRIPT_DIR=%~dp0)&(SET SCRIPT_NAME=%~nx0)&(SET SCRIPT_BASE_NAME=%~n0)&(SET SCRIPT_EXTENSION=%~x0)&(SET SCRIPT_ARGUMENTS=%*)&(POWERSHELL -NoLogo -Sta -NoProfile -ExecutionPolicy Unrestricted "&([scriptblock]::create('$OutputEncoding=[Console]::OutputEncoding;'+\"`n\"+((gc -Encoding UTF8 -Path \"!SCRIPT_PATH!\"|?{$_.readcount -gt 1})-join\"`n\")))" !SCRIPT_ARGUMENTS!)&(SET EXIT_CODE=!ERRORLEVEL!)&POPD&EXIT !EXIT_CODE!&ENDLOCAL&GOTO :EOF

if(!(([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator"))){
    Start-Process -FilePath "cmd.exe" -ArgumentList "/c `"$Env:SCRIPT_PATH`"" -verb runas;
    ### 非管理者で実行させたい内容があればこのあたりに記述 ###
    exit;
}
### 以降、管理者で実行させたいPowerShellを記述 ###

参考にさせて頂いた記事
https://qiita.com/mo1/items/7096a4b5a08d836cf4ad
https://qiita.com/Xiacchi/items/765f032733fe904b1e88

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?