[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[问题求助] 在bat文件中有选择的执行某段PowerShell代码遇到的问题

在国外so找到了一段下面的代码, 可以实现在一个bat文件中有选择的执行某段PS代码

例如下面的例子中,修改 iex($f[2]) 中的数字, 例如,修改为1 执行第一段PS代码【可以让cmd窗口居中】, 修改2 执行第二段PS代码【打开计算器】, 其中 :tag4file: 是分隔符


但是执行下面的第一段代码, 直接报错, 而单独执行又不报错, 求高手指引, 提前感谢!
  1. @set "0=%~f0" &powershell -nop -c $f=[IO.File]::ReadAllText($env:0)-split':tag4file\:.*';iex($f[2]); &pause&exit
  2. :tag4file:
  3. Add-Type -Ty @'
  4.     using System.Runtime.InteropServices;
  5.     public static class WinApi{
  6.         [DllImport("user32.dll")] public static extern bool SetWindowPos(uint hWnd,uint hAfter,uint x,uint y,uint cx,uint cy,uint flags);
  7.         [DllImport("kernel32.dll")] public static extern uint GetConsoleWindow();
  8.     }
  9. '@
  10. $w = [Windows.Forms.Screen]::PrimaryScreen.WorkingArea.Width
  11. [void][WinApi]::SetWindowPos(([WinApi]::GetConsoleWindow()), $null, ($w-996)/2, 0, 996, 186, 0)
  12. :tag4file:
  13. start calc
复制代码
----------------------------------------------------------------------------------------------------------------
下面单独执行PS代码1没有问题
  1. #@&cls&mode con cols=106 lines=8&powershell "gc '%~0'|out-string|iex"&pause&exit
  2. Add-Type @'
  3.     using System.Runtime.InteropServices;
  4.     public static class WinApi{
  5.         [DllImport("user32.dll")] public static extern bool SetWindowPos(uint hWnd,uint hAfter,uint x,uint y,uint cx,uint cy,uint flags);
  6.         [DllImport("kernel32.dll")] public static extern uint GetConsoleWindow();
  7.     }
  8. '@
  9. $w = [Windows.Forms.Screen]::PrimaryScreen.WorkingArea.Width
  10. [void][WinApi]::SetWindowPos(([WinApi]::GetConsoleWindow()), $null, ($w-996)/2, 0, 996, 186, 0)
复制代码
本人所发所有贴子或代码, 诸大侠若认为有改进之处,请不吝赐教,感激不尽!

下面这行代码在Add-Type之前插入
  1. [void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
复制代码

TOP

回复 2# went


   感谢大侠指引, 我用了下面的, 简洁点
Add-Type -AssemblyName System.Windows.Forms
本人所发所有贴子或代码, 诸大侠若认为有改进之处,请不吝赐教,感激不尽!

TOP

返回列表