使用批处理直接运行PowerShell脚本

背景:

作为一名苦逼的运维岗,需要经常写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

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值