在.bat中执行powershell


PowerShell交流中心分类: Powershell基础在.bat中执行powershell
0
LionelZhao asked 8 年 ago

之前从论坛看到用循环查所有IP地址。 于是想做把代码放在.bat中,做到自动查IP地址并弹出窗口 代码如下: $IP=foreach($ip in (ipconfig) -like ‘*IPv4*’) {“IP Address:” + ($ip -split ‘ : ‘)[-1]  };$Showip = New-Object -ComObject WScript.Shell;$Popupwin = $showip.popup(“$IP”,0,”Show IP”,1 + 64) 在powerhslell中可以正常运行。但用如下方法将代码放入bat文件中就无法运行了。 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command {$IP=foreach($ip in (ipconfig) -like ‘*IPv4*’) {“IP Address:” + ($ip -split ‘ : ‘)[-1]  };$Showip = New-Object -ComObject WScript.Shell;$Popupwin = $showip.popup(“$IP”,0,” Show IP”,1 + 64)} 求大神指点~~跪谢~~~

1 Answers
0
Best Answer
Mooser Lee 管理员 answered 8 年 ago

一个PowerShell脚本文件ps1本身就支持右键运行的,为什么要放在bat文件中,而且会有各种语法,参数问题。这就好比修了铁路,结果让让几十匹马带着车皮跑。

正常的做法是,所有的逻辑都写在ps1文件中,然后再用bat作为一个引导程序调用ps1文件。很多人这样做的目的是因为bat双击就可以运行。

如果你一定要不走寻常路,建议使用powershell.exe -encodedCommand 参数,把所有的脚本转换成base64string,这样应当就不会有参数和语法的问题了。(不推荐)

LionelZhao replied 8 年 ago

感谢回复,受ExecutionPolicy限制,无法运行ps1文件,用户为普通用户无法提权,才出此下策。 参考powershell帮助中的方法 $command = “dir ‘c:\program files’ ” $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encodedCommand = [Convert]::ToBase64String($bytes) powershell.exe -encodedCommand $encodedCommand 依然无发运行~~~

Mooser Lee 管理员 replied 8 年 ago

如果仅仅是为了提权,这是不可能完成的,Windows UAC的目的就是让任何的提权都应当在当前登录用户的批准下,这样才安全。你如果要强制一个脚本以管理员权限运行,可以参考:http://www.pstips.net/force-script-run-as-admin.html 但是这仍然需要用户通过鼠标确定。除非你把UAC,彻底关掉,如果是测试机可以做,如果是工作机,强烈不推荐。