0

I am trying to get the downloaded script from an iex expression directly from memory and I think there is something I am missing. $MyInvocation.MyCommand.ScriptBlock should get the current script block.

In the example below it is on one side the thread-function and on the other side the iex-expression. How do I get the things in between? I know that the full script is there somewhere in some kind of thread but i don't get what PowerShell is doing here.

# run-self in iex - 
# two down, one up - or why $MyINvocation after iex is the iex command
# how to get the script itself, not the thread-function nor the iex-cmd
# save this script on webserver and call it with: iex((new-object net.webclient).DownloadString('http://some.url/script.ps1') )

$sharedData = [HashTable]::Synchronized(@{})

$sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$runspacepool = [runspacefactory]::CreateRunspacePool(1,2,$sessionstate,$Host)
$runspacepool.Open()


$selfcallhelper = {
    param($sharedData)
    $sharedData.Mysource = $MyINvocation.MyCommand.ScriptBlock
}

# start thread
$thread = [powershell]::Create().AddScript($selfcallhelper).AddArgument($sharedData)
$thread.RunspacePool = $runspacepool
$thread.BeginInvoke()

# write output to files in current directory
$sharedData.Mysource | out-file "myscript-from-thread.txt"
$MyINvocation.MyCommand.ScriptBlock | out-file "myscript-from-self.txt"
uzi
  • 1

1 Answers1

1

$MyInvocation always refers to the callers context. It's the way a bit of script can ask "who called me?"

It is sometimes useful to know where some script comes from, not who invoked it. In cases like this, you can simply invoke a nested script block, e.g.

$selfcallhelper = {
    param($sharedData)
    $sharedData.Mysource = & { $MyINvocation.MyCommand.ScriptBlock }
}

The change here was to evaluate $MyInvocation inside it's own script block.

Jason Shirk
  • 7,734
  • 2
  • 24
  • 29
  • Thanks for the push. It was soooo simple: $sharedData.Mysource = $MyINvocation.MyCommand.ScriptBlock in the main Block and i've got the full source in every scriptblock and thread. – uzi Jan 17 '14 at 20:21