Run Powershell script via batch file with elevated privileges

谁说胖子不能爱 提交于 2020-01-24 22:20:21

问题


I need to run a Powershell script to create AD user via a batch file. The thing is I need to run this PS script with elevated privileges (domain admin account). I have tried to script a '.bat' file which encloses all this information but I have been unsuccessful so far. Here is the script :

echo off
cls
echo Sign in with your ADM ID
set /p username=

powershell -noprofile -command "&{ start-process powershell -ArgumentList '-
noprofile -file C:\Users\...\Desktop\Powershell_scripts\New-ADuser\New-
Aduser_test.ps1' -verb RunAs}"

I have tried with line /netonly /user:adm@domain but It won't work.

Do you guys have any idea?

Thanks in advance.


回答1:


I have finally ended up with this :

runas.exe /netonly /noprofile /user:domainadm@domain "powershell.exe -
noprofile -File "C:\Users\...\Desktop\Powershell_scripts\New-
ADuser\.ps1" -verb RunAs"

It works like a charm now!

Hope it will help anyone in need. ;)




回答2:


you can start powershell with another credentials

@echo off
cls
echo Sign in with your ADM ID  
set/P user="*     user: "
rem set/P pass="* password: "
set "psCmd=powershell -Command "$pwd = read-host '* password' -AsSecureString; $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd); [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /F "usebackq delims=" %%P in (`%psCmd%`) do set "pass=%%P"

powershell -executionpolicy bypass -Command "$p='%pass%'|convertto-securestring -asplaintext -force;$c=new-object -typename system.management.automation.pscredential('%user%',$p);start-process 'powershell' '-Command "C:\Users\...\Desktop\Powershell_scripts\New-ADuser\New-Aduser_test.ps1"' -credential $c -passthru -wait; read-host;"
exit/B

or simply

@echo off
cls

powershell -executionpolicy bypass -Command "start-process 'powershell' '-Command "C:\Users\...\Desktop\Powershell_scripts\New-ADuser\New-Aduser_test.ps1"' -credential $c -passthru -wait; read-host;"
exit/B

that will prompt for credentials



来源:https://stackoverflow.com/questions/48945292/run-powershell-script-via-batch-file-with-elevated-privileges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!