2017-10-09 293 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地址)