使用.bat文件调用powershell函数

时间:2013-06-11 04:46:40

标签: powershell batch-file

我想知道如何使用.Bat文件调用powershell函数。

我有这个简单的功能:

(Script.ps1)

function testfunction
{
Write-Log "Calling from Bat file"
}

我想在.Bat文件中调用函数testfunction。

powershell。\ Script.ps1 ...

5 个答案:

答案 0 :(得分:4)

我注意到有一个开关-ExecutionPolicy ByPass允许批处理文件使用Powershell运行。这可以在这里使用,取自vonPryz的答案。

@echo off
:: Create a test script file
echo function test { write-host "Called from %~f0" } > s.ps1
powershell -ExecutionPolicy ByPass -command ". "%cd%\s.ps1"; test;"
del s.ps1
pause

答案 1 :(得分:2)

使用-command开关启动Powershell,包含脚本并调用该函数。在调用函数之前,您需要对脚本进行点源。

:: Create a test script file
C:\temp>echo function test { write-host "Called from .bat" } > c:\temp\s.ps1
C:\temp>powershell -command ". c:\temp\s.ps1; test;"
:: Output
Called from .bat

另外,请查看some samples

答案 2 :(得分:0)

我通常这样做:

powershell {Set-ExecutionPolicy unrestricted}
powershell.exe -executionpolicy ByPass ./script/powerhsell-script.ps1 %par1% %par2%
powershell {Set-ExecutionPolicy Restricted}

希望你需要:)

答案 3 :(得分:0)

我已经使用

完成了
powershell.exe -ExecutionPolicy Bypass -file ".\Write_date.ps1"

似乎与其他人写的类似,但我不确定vonPryz在调用脚本之前需要点源脚本的意思。以上工作在Win7上,executepolicy设置为限制。

答案 4 :(得分:0)

我知道这已经很老了,但是最近我试图做同样的事情,所以花了很长时间我才知道该怎么做。答案非常简单

在BatchFile(RunMe)

powershell -command“。Script.ps1; Set-SomeFunction%1%2%3%4%5”

然后您可以像这样调用批处理

RunMe -SomeParm val -SomeParm2 val -SomeSwitch -SomeBool $ true

也,以管理员身份运行

powershell-命令“ Start-Process -verb runas powershell”“'-noexit -command”。 Script.ps1; Set-SomeFunction%1%2%3%4%5%6%7%8%9'“

相关问题