[转载][微调]使用批处理文件为运行外壳运行PowerShell脚本

废话不多说,直接上码:

<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd /d %~dp0
: Invoke this file as powershell expression
::下面这句传递的参数不能有空格,如果有空格应该改成 %1 %2 ... 这种方式传参
::powershell -WindowStyle Hidden -executionpolicy remotesigned -Command "Invoke-Command -ScriptBlock ([scriptblock]::Create($([System.IO.File]::ReadAllText('%~f0')))) -ArgumentList (@(&{$args}%*))"
::下面只支持传递10个参数
powershell -WindowStyle Hidden -executionpolicy remotesigned -Command "Invoke-Command -ScriptBlock ([scriptblock]::Create($([System.IO.File]::ReadAllText('%~f0')))) -ArgumentList (@('%~dp0','%1','%2','%3','%4','%5','%6','%7','%8','%9','%10'))"
::正则表达式(不将单引号或双引号引起来时使用空格分割字符串):[^\s"']+|"([^"]*)"|'([^']*)'
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script
[Cmdletbinding()]
param (
    [Parameter(Mandatory = $false, Position = 0)][string]$CurrentFile
)


# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"

# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
    Write-Host "Exit script..."
    break
}

# example: call standard powershell command
Get-Item .

将代码保存为batch-ps-script.cmd

脚本参考:

https://stackoverflow.com/questions/6037146/how-to-execute-powershell-commands-from-a-batch-file
https://stackoverflow.com/questions/13724940/how-to-run-a-powershell-script-from-the-command-line-and-pass-a-directory-as-a-p
https://stackoverflow.com/questions/51934047/execute-a-remote-generic-powershell-script-with-generic-parameters
https://stackoverflow.com/a/57572270

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值