背景:
作为一名苦逼的运维岗,需要经常写PowerShell脚本,自己写自己用,完美闭环,这本来没什么问题,但是由于项目、公司等等一系列的变更需求,这些脚本需要分发给普通用户使用,由于PowerShell脚本的运行有局限性,用户使用会有各种各样的问题,因此研究通过批处理直接运行PowerShell脚本。
思路:
1、考虑到易用性,给用户的必须是单个文件,因此通过批处理直接打开PowerShell脚本文件的方法行不通;
2、由于批处理涉及写入、删除等动作,因此批处理运行时需要自动提权;
3、PowerShell的运行依赖电脑的安全策略,默认不能运行,因此需要变更执行策略,使得电脑可以运行PowerShell脚本;
方法:
1、批处理中提权:
%1 start "" mshta vbscript:createobject("shell.application").shellexecute("""%~0""","::",,"runas",1)(window.close)&exit
2、变更电脑的执行策略,使得能够执行Powershell脚本:
PowerShell -Command "Set-ExecutionPolicy RemoteSigned -Scope CurrentUser"
3、批处理中通过“more”命令生成PowerShell脚本,生成完成之后再执行Powershell脚本,示例:
more +2 %0 > ps.ps1
Powershell -File "ps.ps1"
4、及时删除生成的PowerShell文件:
Remove-Item $MyInvocation.MyCommand.Path -Force
示例:
@echo off
%1 start "" mshta vbscript:createobject("shell.application").shellexecute("""%~0""","::",,"runas",1)(window.close)&exit
cd /d %~dp0
PowerShell -Command "Set-ExecutionPolicy RemoteSigned -Scope CurrentUser"
more +7 %0 > PSScripts.ps1
Powershell -File "PSScripts.ps1"
Remove-Item $MyInvocation.MyCommand.Path -Force
Write-Host "Hello,$env:USERNAME,看到这句话说明执行成功了,按回车键退出。。。" -ForegroundColor white -NoNewline
Read-Host