powershell自动启动进程至另外一个监视器

这个博客介绍了如何使用PowerShell创建内存中的模块和函数,以便定义和交互操作未管理的Win32函数。通过`New-InMemoryModule`、`func`和`Add-Win32Type`辅助函数,可以方便地在PowerShell中调用和管理Windows API。示例展示了如何定义并使用这些函数来创建RDP连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function New-InMemoryModule
{
<#
.SYNOPSIS
Creates an in-memory assembly and module
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
When defining custom enums, structs, and unmanaged functions, it is
necessary to associate to an assembly module. This helper function
creates an in-memory module that can be passed to the 'enum',
'struct', and Add-Win32Type functions.
.PARAMETER ModuleName
Specifies the desired name for the in-memory assembly and module. If
ModuleName is not provided, it will default to a GUID.
.EXAMPLE
$Module = New-InMemoryModule -ModuleName Win32
#>
	
	[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
	[CmdletBinding()]
	Param (
		[Parameter(Position = 0)]
		[ValidateNotNullOrEmpty()]
		[String]$ModuleName = [Guid]::NewGuid().ToString(),
		[Parameter(Position = 1)]
		[Switch]$AlwaysNew
	)
	
	$AppDomain = [Reflection.Assembly].Assembly.GetType('System.AppDomain').GetProperty('CurrentDomain').GetValue($null, @())
	$LoadedAssemblies = $AppDomain.GetAssemblies()
	if (-not $AlwaysNew)
	{
		foreach ($Assembly in $LoadedAssemblies)
		{
			if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName))
			{
				return $Assembly
			}
		}
	}
	$DynAssembly = New-Object Reflection.AssemblyName($ModuleName)
	$Domain = $AppDomain
	$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')
	$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)
	
	return $ModuleBuilder
}

# A helper function used to reduce typing while defining function
# prototypes for Add-Win32Type.
function func
{
	Param (
		[Parameter(Position = 0, Mandatory = $True)]
		[String]$DllName,
		[Parameter(Position = 1, Mandatory = $True)]
		[string]$FunctionName,
		[Parameter(Position = 2, Mandatory = $True)]
		[Type]$ReturnType,
		[Parameter(Position = 3)]
		[Type[]]$ParameterTypes,
		[Parameter(Position = 4)]
		[Runtime.InteropServices.CallingConvention]$NativeCallingConvention,
		[Parameter(Position = 5)]
		[Runtime.InteropServices.CharSet]$Charset,
		[String]$EntryPoint,
		[Switch]$SetLastError
	)
	
	$Properties = @{
		DllName		    = $DllName
		FunctionName    = $FunctionName
		ReturnType	    = $ReturnType
	}
	
	if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }
	if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }
	if ($Charset) { $Properties['Charset'] = $Charset }
	if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }
	if ($EntryPoint) { $Properties['EntryPoint'] = $EntryPoint }
	
	New-Object PSObject -Property $Properties
}
function Add-Win32Type
{
<#
.SYNOPSIS
Creates a .NET type for an unmanaged Win32 function.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: func
.DESCRIPTION
Add-Win32Type enables you to easily interact with unmanaged (i.e.
Win32 unmanaged) functions in PowerShell. After providing
Add-Win32Type with a function signature, a .NET type is created
using reflection (i.e. csc.exe is never called like with Add-Type).
The 'func' helper function can be used to reduce typing when defining
multiple function definitions.
.PARAMETER DllName
The name of the DLL.
.PARAMETER FunctionName
The name of the target function.
.PARAMETER EntryPoint
The DLL export function name. This argument should be specified if the
specified function name is different than the name of the exported
function.
.PARAMETER ReturnType
The return type of the function.
.PARAMETER ParameterTypes
The function parameters.
.PARAMETER NativeCallingConvention
Specifies the native calling convention of the function. Defaults to
stdcall.
.PARAMETER Charset
If you need to explicitly call an 'A' or 'W' Win32 function, you can
specify the character set.
.PARAMETER SetLastError
Indicates whether the callee calls the SetLastError Win32 API
function before returning from the attributed method.
.PARAMETER Module
The in-memory module that will host the functions. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER Namespace
An optional namespace to prepend to the type. Add-Win32Type defaults
to a namespace consisting only of the name of the DLL.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$FunctionDefinitions = @(
  (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),
  (func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),
  (func ntdll RtlGetCurrentPeb ([IntPtr]) @())
)
$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'
$Kernel32 = $Types['kernel32']
$Ntdll = $Types['ntdll']
$Ntdll::RtlGetCurrentPeb()
$ntdllbase = $Kernel32::GetModuleHandle('ntdll')
$Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')
.NOTES
Inspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189
When defining multiple function prototypes, it is ideal to provide
Add-Win32Type with an array of function signatures. That way, they
are all incorporated into the same in-memory module.
#>
	
	[OutputType([Hashtable])]
	Param (
		[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
		[String]$DllName,
		[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
		[String]$FunctionName,
		[Parameter(ValueFromPipelineByPropertyName = $True)]
		[String]$EntryPoint,
		[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
		[Type]$ReturnType,
		[Parameter(ValueFromPipelineByPropertyName = $True)]
		[Type[]]$ParameterTypes,
		[Parameter(ValueFromPipelineByPropertyName = $True)]
		[Runtime.InteropServices.CallingConvention]$NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,
		[Parameter(ValueFromPipelineByPropertyName = $True)]
		[Runtime.InteropServices.CharSet]$Charset = [Runtime.InteropServices.CharSet]::Auto,
		[Parameter(ValueFromPipelineByPropertyName = $True)]
		[Switch]$SetLastError,
		[Parameter(Mandatory = $True)]
		[ValidateScript({ ($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly]) })]
		$Module,
		[ValidateNotNull()]
		[String]$Namespace = ''
	)
	
	BEGIN
	{
		$TypeHash = @{ }
	}
	
	PROCESS
	{
		if ($Module -is [Reflection.Assembly])
		{
			if ($Namespace)
			{
				$TypeHash[$DllName] = $Module.GetType("$Namespace.$DllName")
			}
			else
			{
				$TypeHash[$DllName] = $Module.GetType($DllName)
			}
		}
		else
		{
			# Define one type for each DLL
			if (!$TypeHash.ContainsKey($DllName))
			{
				if ($Namespace)
				{
					$TypeHash[$DllName] = $Module.DefineType("$Namespace.$DllName", 'Public,BeforeFieldInit')
				}
				else
				{
					$TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')
				}
			}
			
			$Method = $TypeHash[$DllName].DefineMethod(
				$FunctionName,
				'Public,Static,PinvokeImpl',
				$ReturnType,
				$ParameterTypes)
			
			# Make each ByRef parameter an Out parameter
			$i = 1
			foreach ($Parameter in $ParameterTypes)
			{
				if ($Parameter.IsByRef)
				{
					[void]$Method.DefineParameter($i, 'Out', $null)
				}
				
				$i++
			}
			
			$DllImport = [Runtime.InteropServices.DllImportAttribute]
			$SetLastErrorField = $DllImport.GetField('SetLastError')
			$CallingConventionField = $DllImport.GetField('CallingConvention')
			$CharsetField = $DllImport.GetField('CharSet')
			$EntryPointField = $DllImport.GetField('EntryPoint')
			if ($SetLastError) { $SLEValue = $True }
			else { $SLEValue = $False }
			
			if ($PSBoundParameters['EntryPoint']) { $ExportedFuncName = $EntryPoint }
			else { $ExportedFuncName = $FunctionName }
			
			# Equivalent to C# version of [DllImport(DllName)]
			$Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])
			$DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,
				$DllName, [Reflection.PropertyInfo[]] @(), [Object[]] @(),
				[Reflection.FieldInfo[]] @($SetLastErrorField,
					$CallingConventionField,
					$CharsetField,
					$EntryPointField),
				[Object[]] @($SLEValue,
					([Runtime.InteropServices.CallingConvention]$NativeCallingConvention),
					([Runtime.InteropServices.CharSet]$Charset),
					$ExportedFuncName))
			
			$Method.SetCustomAttribute($DllImportAttribute)
		}
	}
	
	END
	{
		if ($Module -is [Reflection.Assembly])
		{
			return $TypeHash
		}
		
		$ReturnTypes = @{ }
		
		foreach ($Key in $TypeHash.Keys)
		{
			$Type = $TypeHash[$Key].CreateType()
			
			$ReturnTypes[$Key] = $Type
		}
		
		return $ReturnTypes
	}
}
Function New-RDP
{
	[OutputType('System.Diagnostics.Process')]
	Param ()	
	$ret = Add-Type -AssemblyName System.Windows.Forms 
	$Mod = New-InMemoryModule -ModuleName Win32 -AlwaysNew 
	$FunctionDefinitions = @((func user32 SetWindowPos ([bool]) @([IntPtr], [IntPtr], [int], [int], [int], [int], [int]))) 
	$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32' 
	$user32 = $Types['user32'] 
	$ret =[System.Diagnostics.Process]::GetProcessesByName("wfreerdp") | ForEach-Object { $_.Kill() } 
	$view = New-Object System.Diagnostics.Process 
	$view.EnableRaisingEvents = $true
	$view.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Maximized 
	$view.StartInfo.CreateNoWindow = $false
	$view.StartInfo.FileName = "F:\dl\wfreerdp.exe"
	$view.StartInfo.Arguments = "/f /v:127.0.0.1 /u:Administrator /p:123456"
	#    $view.StartInfo.FileName = "mspaint.exe"
	$view.StartInfo.UseShellExecute = $false;
	$view.Start() 
	$view.WaitForInputIdle() 
	$secondMonitor = [System.Windows.Forms.Screen]::AllScreens[1].Bounds 
	$ret =[System.Threading.Thread]::Sleep(5000) 
	$ret = $user32::SetWindowPos($view.MainWindowHandle, [System.IntPtr]::Zero, $secondMonitor.Left, $secondMonitor.Top, $secondMonitor.Width, $secondMonitor.Height, 0x0040) 
	return $view
}

while ($true)
{
	$view = (New-RDP)[-1]
	$view.WaitForExit()
}	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值