Sunday, May 11, 2014

All about PowerShell ScriptBlock

ScriptBlock is a powerful concept in PowerShell, often misunderstood or not fully exploited. I thought of writing about a generic function “Wait”, since that depends on ScriptBlock, I decided to write about ScriptBlock. In the next blog, I will introduce you to “Wait”. A ScriptBlock is a collection of statements or expressions that can be used as a single unit. It can be saved in a variable, can be passed to function and can be executed remotely. This blog explores some of these aspects of a ScriptBlock.

Basics

ScriptBlock is a collection of statements between “{“ and “}”. It can be saved in a variable and executed using the call operator “&”. The same block can be executed multiple times.

$scriptblock = { "Hello World" }
& $scriptblock
& $scriptblock


Output:

Hello World
Hello World


ScriptBlock with Parameters

ScriptBlock supports param block just like a function.

$scriptBlock = { param ($message) "Hello $message!" }
& $scriptBlock -Message World


Output:

Hello World!


Variable Scoping

Unlike many languages ScriptBlock references variables dynamically as opposed to capturing current variables. Variables are not evaluated when the ScriptBlock is defined, instead it references the latest value of the variable.

$i = 2
$scriptblock = { "Value of i is $i" }
$i = 3
& $scriptblock # ScriptBlock refers to current values which is 3
$i = 4
& $scriptblock # ScriptBlock refers to current values which is 4


Output:

Value of i is 3
Value of i is 4


Behavior of updating a variable inside a ScriptBlock is consistent with rest of PowerShell. (e.g.) updating a variable in the function. Updates are not reflected in the parent scope with the “&” (call) operator, while the “.” (dot) updates the current scope.

$i = 2
$scriptblock = { $i = $i + 1 }
& $scriptblock
$i

. $scriptblock
$i


Output:

2
3


Closure

From Wikipedia, “In programming languages, a closure is a function or reference to a function together with a referencing environment. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside its immediate lexical scope.”

PowerShell offers GetNewClosure that returns a ScriptBlock with captured variables. In that sense PowerShell offers best of both worlds. The following code fragment illustrates that.


$i = 2
$scriptblock = { "Value of i is $i" }.GetNewClosure()
$i = 3
& $scriptblock # To capture the vairables use GetNewClosure


The output of the above script is shown below. Note without closure, ScriptBlock would have referenced the updated value 3.

Value of i is 2


ScriptBlock R-Value

If you used static code blocks in other languages like C/C#, you might be surprised to see the behavior of ScriptBlock definition (without assignment). In PowerShell, if the r-value is not assigned to a variable it is spit out to stdout. Let us look at an example “$i=1+2; $i”. In this case the first statement the r-value “1+2” is assigned to a variable $i. In the second statement “$i”, which is the r-value, since it is not assigned to a variable, the value of that is spit out to stdout.

ScriptBlock definition is really a r-value. Just defining a ScriptBlock means, it is a r-value, hence spit out to stdout without executing it. This might be confusing at first, until the concept is understood (certainly I was surprised!). To execute a ScriptBlock you can use the call operator “&”. Following code demonstrates this concept.

PS C:\> { $i = 1+2; $i }
 $i = 1+2; $i

PS C:\> &{ $i = 1+2; $i }
 3

PS C:\> { $i = 1+2; $i }.ToString()
 $i = 1+2; $i


Invoke-Command & Using

As seen before the ScriptBlock variables has dynamic scope. However the behavior with Invoke-Command is different. Since the execution happens in a different session, for efficiency reasons all the variables in the current scope is not copied to the remote session by default. If a variables has to be copied to the session, it has to be explicitly prefixed with “using:”.

#Create a new session
$s = New-PSSession -ComputerName host1 -Credential $cred

$t1 = 1
$sb = { "t1=$t1" }

#invoke the scriptblock locally
& $sb

#invoke the scriptblock remotely
Invoke-Command -Session $s -ScriptBlock $sb

#invoke the scriptblock remotely with 'using'
$sb = { "t1=$using:t1" }
Invoke-Command -Session $s -ScriptBlock $sb

Remove-PSSession $s


Output from the above script:

t1=1
t1=
t1=1


Explore & Enjoy!
/Siva

61 comments:

  1. One addition: inside a PowerShell code block you can define Begin, Process and End code blocks for pipeline processing...

    PS C:\> $codeblock = {
    begin { Write-Output 'Start' }
    process {Write-Output $_ }
    end { Write-Output 'Finished' }
    }
    PS C:\> 1,2,3 | & $codeblock
    Start
    1
    2
    3
    Finished
    PS C:\>

    ReplyDelete
  2. Can I use pipline in scriptblock ? How do that ?

    ReplyDelete
  3. Red color is difficult to read

    ReplyDelete
  4. How to test script blocks , i can see only output when i run script block but i want to debug, could you please pass information how to do that ?

    ReplyDelete
  5. Great and excellent article. I got more knowledge from this article.recognition a lot for sharing this feature with usPython Online Training
    Learn Python Online

    ReplyDelete
  6. • Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online Training Hyderabad

    ReplyDelete
  7. Excellent, simple yet rich explanation -> elegant!

    ReplyDelete

  8. Nuvigil smart drug is the trade name for Armodafinil smart drug and is the enantiopure compound of Modafinil. There are a number of health benefits that the use of Nuvigil smart drug has to offer to its users. So, you can buy Nuvigil online. The use of the smart drug is safe and has no health issues attached to its usage. In the year 2006, the FDA approved the use of generic Nuvigil smart drug to be used to treat a number of mental issues. Buy Nuvigil online as the use of Nuvigil smart drug has long effect when compared to other smart drugs. This is mainly because Armodafinil smart drug has a longer half-life than the other smart drugs. Therefore more and more people are depending on Nuvigil smart drug to carry on their daily routine smoothly.
    Buy Nuvigil online

    ReplyDelete
  9. After all that I have passed I want to give you a recommendation. check this website for a useful tips!

    ReplyDelete
  10. Norton.com/Setup is  best  antivirus available in the market. If you want to protect your system online or locally from any unforeseen events   Norton.com/Setup   is is a must have software in your PC or Mac. 

    ReplyDelete
  11. McAfee.com/Activate Since the world is developing each day with new computerized advances, digital dangers, malware, information, and harming diseases have additionally turned out to be increasingly more progressed with every day. These digital contamination's harm a gadget or documents in different ways. McAfee.com/Activate  follows the concept of refine your system, you don’t need to worry about data loss or system failure because of the malfunctions. McAfee.com/Activate   works finely on every system including android and ios and supports device like, computer, laptops, mobile phones and tablets.

    ReplyDelete
  12. Install your office.com/Setup by downloading now. Microsoft Office applications are a complete package if multiple integrations like Microsoft Office, Microsoft Power Point, Microsoft Excel etc. All of these programs have their own features and speciality and are used in a lot of industries, small organizations and big organizations.

    ReplyDelete
  13. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

    norton.com/setup

    norton.com/setup

    mcafee.com/activate

    kaspersky activation code

    pogo not loading

    roadrunner email

    aol mail password recovery

    ReplyDelete
  14. American students can contact us to get good grades in Java Assignment Help. We will also help you with cheap online assistance at affordable prices by professional experts

    ReplyDelete
  15. Assignment Help Sydney at the best cost. Assignment composing administrations by our local scholars. Secure your A+ Grade. We give On-Time Delivery. Believed task assist Sydney with adjusting we give. Request Now!

    ReplyDelete
  16. Lucky Patcher smile could be a must-have hacking app for all the crazy gamers is Lucky Patcher Apk. This app helps in modifying most of the android games so the games will be enjoyed to the fullest you can also check How to Use Lucky patcher.

    ReplyDelete
  17. Hello, thanks a lot for sharing this interesting and inspiring ideas. Frankly speaking, I want to say that they are really great. After I will complete my price controls in the florida orange market sample task.

    ReplyDelete
  18. Many of my friends use this site https://superessay.org. I think this is the best site to find an essay or article. Many tasks and no free time. Additional information is required.

    ReplyDelete
  19. I really happy found this website eventually. Really informative and inoperative, Thanks for the post and effort! Please keep sharing more such blog.

    norton.com/setup

    norton.com/setup

    mcafee.com/activate

    roadrunner email

    aol mail password recovery

    mcafee.com/activate

    ReplyDelete
  20. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..


    azure tutorial

    ReplyDelete
  21. Below is a list of decorative materials and under them are notes to give more elaborate descriptions of such materials and the perfect work of decoration they provide in the engineering fields which each of them is applied to:freelance writer for hire

    ReplyDelete
  22. My self, William Smith Associated with Livewebtutors. Which Is Known as A Renowned java assignment help Australia Company. I Have Been Working as A Full-Time Academic Consultant from Last Ten Years. Livewebtutors Is an Experienced and Highly Reputable All Assignment Help Provider in Australia, Specialized in Academic Writing. We Offer High-Quality Service and Supply Free Plagiarism Report for All Assignments and Best Price.

    ReplyDelete
  23. I am very impressed by this post; this site has always been pleasant news for everyone. Thank you very much for such an encouraging post. Keep sharing, great job!
    assignment help

    ReplyDelete
  24. Substance Painter License Key
    also introduced “dynamic strokes,” a new way to draw complex materials and environments. With dynamic strokes, brushes evolve over time to increase the uniqueness of 3D resources and use the artist’s own parametric directions to guide it. Instead of drawing each individual leaf and branch of ivy, placing an ivy asset will see the vegetation expanding into lush overgrowth. The footprint on the beach will soon turn into a path to the distance, and this is just the beginning. Dynamic strokes can help create trim modes or randomly place extensions, all within the setup parameters. Time clues can also be taken into account, helping the brush fade out, changing color and distortion, depending on how long the artist has drawn. Moreover, the new feature comes with 20 preset assets that encourage artists to create their own assets.

    ReplyDelete
  25. Make use of Java Assignment Help services provided by experienced java programmers. Meet all your project requirements by placing your order for online writing services.
    Java Programming Help
    Programming Help
    Programming Assignment Help

    ReplyDelete
  26. HP LaserJet, officeJet and envy printers are famous for its printing quality. If you want to do HP Wireless Printer Setup without any technical error then get help from experts to setup it.

    ReplyDelete
  27. Use Assignment Help to connect with Australian academic writers in just a few minutes. Students can take online assignment writing services in Australia when they have no one to ask their queries and find it tough to write your academic papers.
    My Assignment Help
    Assignment Help Online
    Online Assignment Help

    ReplyDelete
  28. Thanks for posting this article. The previous post that I read was behind the formaldehyde curtain. It was so boring but it was my task for college lesson.

    ReplyDelete
  29. Excellent information Providing by your blog, thank you for taking the time to share with us such a nice information.
    Best College Writing Service

    ReplyDelete
  30. online assignment help in Australia that ensures that you meet the deadline every time. It is important that the assignments are written in a way that all the questions asked by your professor are answered and all the objectives are fulfilled. Our subject experts make sure that we do not deviate from the actual context of the assignment and provide the best possible solution without charging an exorbitant amount. Our fair pricing and discounts make our services even more accessible and the best choice when availing the online assignment help in Australia. We consider it a sign of discipline to meet the deadline and submit top quality work within the designated time limit. The subject experts at assignment work help deliver the required output to meet the expectations of our clients every time and make sure that you get good marks for every assignment.
    online assignment writing help
    assignment solution australia
    assignment help australia
    online assignment help
    best assignment help
    assignment work help usa
    assignment work services asutralia

    ReplyDelete
  31. This list of the best love quotes of all time is sure to make it easier to express your emotions and feelings of love to your partner. These famous inspirational love quotes and sayings will help you describe exactly how you are feeling with the most simple wording.

    ReplyDelete
  32. Online psychology paper writing service companies are very keen when it comes to Psychology Research Paper Services for students stuyding psychology studies in order for them to score straight A’s in their custom psychology research papers.

    ReplyDelete
  33. Hey What A Great Article Mplyrics

    Hey What A Great Article Mrpendus

    ReplyDelete
  34. Thank you for sharing such a nice and interesting blog with us regarding Python. I have seen that all will say the same thing repeatedly. Java training in chennai But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle.
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  35. Abc Assignment Help is connected to dedicated team of Law Professionals for helping students with their academic task. We provide best online contract Law assignment help with 100% accuracy. Our team cover all topics under contract law. They have till date accomplish all the assignments and questions provided in contract law. Under professional guidance students receive assignment with superior quality content. For timely assistance and quality work, connect with online members.

    ReplyDelete
  36. Online cultural studies writing services have become very popular among Cultural Coursework Writing Service students seeking Cultural Studies Research Paper Services and cultural studies essay writing services.

    ReplyDelete
  37. If you are facing Gmail not receiving emails on a daily basis, our technical professionals are technically known for resolving this issue efficiently. Our techies are always available to help you with any kind of technical troubles.

    ReplyDelete
  38. Whether you want to set up a centurylink webmailor you want to delete it, you can do it by yourself. Simply, you need to go through the steps discussed in the blog regarding the set and deletion of your account.

    ReplyDelete
  39. My job is to send the business proposals to the domestic and global clients, so I rely on yahoo mail services. I want to understand IMAP settings for my yahoo emailing services. I don’t have ideas about yahoo imap settings. Can anyone have the relevant answers for yahoo imap settings?

    ReplyDelete
  40. I know very well that Garmin GPS is very easy and efficient in using, so I am very comfortable in using all the functions of Garmin GPS unit in the right ways. But from a few days, my unit is not showing the right signal to find out the desired destinations exactly. So, I want to Update Garmin GPS unit in the right ways. Can anyone help me to update Garmin GPS unit in the simple ways?

    ReplyDelete
  41. NovaPoker Adalah Situs Judi Poker Terbaik Dengan Taruhan Uang Asli Yang Menjaminkan Kemenangan Yang Tinggi

    ReplyDelete
  42. I use AOL emailing service for smooth and clear communication. But from the last three or four weeks, my AOL mail is not working, so I am extremely disappointed.

    ReplyDelete
  43. In this blog, we will be casting light upon the latest updates on the Facebook Algorithm in 2020. The following content is an effective medium for the Brands who want to optimize their opportunity on social media considering Facebook advertising and formulating social media strategies in the new decade.

    FB Latest Algorithm Update 2020
    Facebook Algorithm Work In 2020
    facebook changes
    facebook algorithm
    facebook algorithm change
    facebook bypass

    ReplyDelete
  44. Choose Assignment Help when you have no one to ask your concerns while studying at American universities. Students can connect with professional academic writers using online assignment writing services and discuss their concerns even staying at home. You don’t need to make any physical contact with anyone when you have the option of online services.
    Assignment Helper | Assignments Help | Help with assignment

    ReplyDelete
  45. Jendral poker adalah agen judi yang terpercaya di server PKV dengan persentase kemenangan yang tinggi.

    Whatsapp: +855 8731 8883

    ReplyDelete
  46. To seek the best Psychology Research Writing Services for those studying psychology writing services, it is important to hire award winning psychology paper writing help services.

    ReplyDelete
  47. Due to some AOL IMAP Settings problems, I am getting problems to open them appropriately. I have taken online help from AOL technicians, but nothing is successful. Hence, it has become a big issue for me. Can you advise the best solutions for solving settings problems?

    ReplyDelete
  48. Myassignmenthelp is the proficient academic writing service holding a ingenious team of more than 3,000 assignment tutors, dedicated to assist students with the authentic my assignment help services. Our specialised team for my assignment help Australia team is available 24x7 to help students on a plethora of assignments, essays, coursework and more.

    ReplyDelete
  49. You have made quite an interesting article. It's nice shared information and it's quite helpful post. I like the layout and flow of the write-up, because it kept me involved this whole time. At My Assignment Help Au, We Offer Pocket-Friendly Services And Write Tailored Assignments. Students Trust Our Assignment Help in Australia. To Get Authentic Assignments Within Deadlines, Hire Us Today!

    ReplyDelete
  50. I will be happy to help you with connecting your HP envy 4520 printer to a wireless network. It’s simple if followed patiently and can be completed in a few steps. Firstly, you need to ensure that your envy 4520 is connected directly to the wall socket.

    ReplyDelete
  51. Are you struggling to configure bellsouth email settings to your Microsoft Outlook? Then, you are not alone. There are loads of other people facing exactly the same issue on their android, iPhone, and iPad devices.

    ReplyDelete
  52. If the printer driver is unavailable error message appears on your screen, it means you have installed incompatible drivers or the present drivers are outdated. Many users face this problem while installing the printer. this message tells that device is not able to detect the correct printer driver, To get rid from this problem you need to perform a clean install and see if you can set up your printer or not. For this, you need to uninstall the printer entries and then install it again. If you still face difficulty then you can contact to our customer support team.

    ReplyDelete