hah...:P
MSH doesn't directly support P/Invoke. The easiest way to use P/Invoke from
MSH is probably to create a DLL in C#/VB/etc and call that from MSH.
But if you really want to use P/Invoke from MSH, it is possible with
Reflection.Emit. But note that the dynamic assembly created can't be
unloaded (unless you create it in a new AppDomain and unload that).
Here is an example that calls the user32.dll MessageBox API:
$domain = [AppDomain]::CurrentDomain
$name = New-Object Reflection.AssemblyName 'TestAssembly'
$assembly = $domain.DefineDynamicAssembly($name, 'Run')
$module = $assembly.DefineDynamicModule('TestModule')
$type = $module.DefineType('TestType')
[Type[]]$parameterTypes = [IntPtr], [string], [string], [int]
$method = $type.DefineMethod("MessageBox", 'Public,Static,PinvokeImpl',
[int], $parameterTypes)
$ctor =
[Runtime.InteropServices.DllImportAttribute].GetConstructor([string])
$attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor, 'user32'
$method.SetCustomAttribute($attr)
$realType = $type.CreateType()
[object[]]$args = [IntPtr]0, [string]'Bar', [string]'Foo', [int]0
$realType.InvokeMember('MessageBox', 'Public,Static,InvokeMethod', $null,
$null, $args)
(A less verbose way would probably be to generate C#/VB code, compile that
with csc.exe/vbc.exe and load the assembly.)
BTW, you can cast ScriptBlocks to delegates.
--
Jeff Jones [MSFT]
Microsoft Command Shell Development
Microsoft Corporation
This posting is provided "AS IS" with no warranties, and confers no rights.
"hayate" <haya...@gmail.com> wrote in message
news:1129084134.0...@g47g2000cwa.googlegroups.com...
$ad = [AppDomain]::CreateAppdomain('NewDomain')
$delegate = New-Object CrossAppDomainDelegate($Script) # maybe it's
wrong,it can't execute here
$ad.DoCallBack($delegate)
[AppDomain]::Unload($ad)
that's all. I don't how to cast a scriptblock to delegate,so I have
tried some ways.