批处理之家's Archiver

5i365 发表于 2022-4-2 22:14

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

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

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


[size=12px]但是执行下面的第一段代码, 直接报错, 而单独执行又不报错, 求高手指引, 提前感谢![/size][code]@set "0=%~f0" &powershell -nop -c $f=[IO.File]::ReadAllText($env:0)-split':tag4file\:.*';iex($f[2]); &pause&exit
:tag4file:
Add-Type -Ty @'
    using System.Runtime.InteropServices;
    public static class WinApi{
        [DllImport("user32.dll")] public static extern bool SetWindowPos(uint hWnd,uint hAfter,uint x,uint y,uint cx,uint cy,uint flags);
        [DllImport("kernel32.dll")] public static extern uint GetConsoleWindow();
    }
'@
$w = [Windows.Forms.Screen]::PrimaryScreen.WorkingArea.Width
[void][WinApi]::SetWindowPos(([WinApi]::GetConsoleWindow()), $null, ($w-996)/2, 0, 996, 186, 0)

:tag4file:
start calc[/code]----------------------------------------------------------------------------------------------------------------
下面单独执行PS代码1没有问题[code]#@&cls&mode con cols=106 lines=8&powershell "gc '%~0'|out-string|iex"&pause&exit

Add-Type @'
    using System.Runtime.InteropServices;
    public static class WinApi{
        [DllImport("user32.dll")] public static extern bool SetWindowPos(uint hWnd,uint hAfter,uint x,uint y,uint cx,uint cy,uint flags);
        [DllImport("kernel32.dll")] public static extern uint GetConsoleWindow();
    }
'@
$w = [Windows.Forms.Screen]::PrimaryScreen.WorkingArea.Width
[void][WinApi]::SetWindowPos(([WinApi]::GetConsoleWindow()), $null, ($w-996)/2, 0, 996, 186, 0)
[/code]

went 发表于 2022-4-2 22:34

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

5i365 发表于 2022-4-2 22:49

[b]回复 [url=http://www.bathome.net/redirect.php?goto=findpost&pid=253755&ptid=62215]2#[/url] [i]went[/i] [/b]


   感谢大侠指引, 我用了下面的, 简洁点
Add-Type -AssemblyName System.Windows.Forms

页: [1]

Powered by Discuz! Archiver 7.2  © 2001-2009 Comsenz Inc.