2017-10-09 292 views
0

我想通过批处理文件运行PowerShell脚本。我想这样做,因为我想让我的回声能够打开我的电脑。 (可能有更简单的方法来从回声发送WOL请求,但我想通过PowerShell来进行学习)通过批处理文件运行WOL PowerShell脚本

对于WOL命令我有这个(我确实有破折号的正确值,我只是不希望向他们展示):

Send-WOL -mac ------- -ip -------- 

然后我.bat文件包含此:

@ECHO OFF 
SET ThisScriptsDirectory=%~dp0 
SET PowerShellScriptPath=%ThisScriptsDirectory%script.ps1 
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'"; 
pause 

现在,当我运行.bat文件,我会得到这个错误:

 
Send-WOL : The term 'Send-WOL' is not recognized as the name of a cmdlet, 
function, script file or operable program. Check the spelling of the name, 
or if a path was included, verify that the path is correct and try again. 
At C:\Users\hao\Desktop\WOL main\Script.ps1:1 char:1 
+ Send-WOL -mac █████████████████ -ip █████████████ 
+ ~~~~~~~~ 
    + CategoryInfo   : ObjectNotFound: (send-WOL:String) [], CommandNotFoundExeption 
    + FullyQualifiedErrorId : CommandNotFoundExeption 

Press any key to continue . . . 

即使当我在脚本中放入完全相同的命令时,手动进入PowerShell也能正常工作。

+0

PowerShell找不到'Send-WOL.ps1',可能是因为它的位置不在PATH中,或者是因为您将该脚本中的代码放入了您的配置文件中(您告诉批处理文件不加载)。 –

+0

为什么使用'-Command'而不是'-File'? '@Powershell -NoProfile -ExecutionPolicy Bypass -File%〜dp0script.ps1',_如果路径中包含spaces_,则使用引号。如果你想使用'-Command',那么根本就不需要使用'.ps1'文件! '@Powershell -NoProfile -ExecutionPolicy Bypass -Command“Send-WOL -mac ------- -ip --------”'。 – Compo

+0

尝试添加'Set-Location $ PSScriptRoot'到您的script.ps1文件 – TToni

回答

0

假设外部脚本位于C:\下载,试试这个在批处理文件:

Powershell -File "C:\Downloads\Send-WOL.ps1" -mac ------- -ip -------- 
0

与所有的帮助下,我终于弄明白。

@ECHO OFF 
powershell -executionpolicy bypass -file "---------------" 

这是在bat文件(与下面的电源外壳脚本的路径替换破折号)

function Send-WOL 
{ 
<# 
    .SYNOPSIS 
    Send a WOL packet to a broadcast address 
    .PARAMETER mac 
    The MAC address of the device that need to wake up 
    .PARAMETER ip 
    The IP address where the WOL packet will be sent to 
    .EXAMPLE 
    Send-WOL -mac 00:11:32:21:2D:11 -ip 192.168.8.255 
#> 

[CmdletBinding()] 
param(
[Parameter(Mandatory=$True,Position=1)] 
[string]$mac, 
[string]$ip="255.255.255.255", 
[int]$port=9 
) 
$broadcast = [Net.IPAddress]::Parse($ip) 

$mac=(($mac.replace(":","")).replace("-","")).replace(".","") 
$target=0,2,4,6,8,10 | % {[convert]::ToByte($mac.substring($_,2),16)} 
$packet = (,[byte]255 * 6) + ($target * 16) 

$UDPclient = new-Object System.Net.Sockets.UdpClient 
$UDPclient.Connect($broadcast,$port) 
[void]$UDPclient.Send($packet, 102) 

} 

send-wol -mac ------ -ip -------- 

此被包含在电源外壳脚本中(取代与MAC破折号和目标计算机的IP地址)