{"id":47,"date":"2009-03-15T21:34:53","date_gmt":"2009-03-16T03:34:53","guid":{"rendered":"http:\/\/jameskovacs.com\/2009\/03\/16\/Writing+Reusable+Scripts+With+PowerShell"},"modified":"2009-03-15T21:34:53","modified_gmt":"2009-03-16T03:34:53","slug":"writing-reusable-scripts-with-powershell","status":"publish","type":"post","link":"https:\/\/www.jameskovacs.com\/index.php\/2009\/03\/15\/writing-reusable-scripts-with-powershell\/","title":{"rendered":"Writing Re-usable Scripts with PowerShell"},"content":{"rendered":"<p>Continuing on from <a href=\"2009\/02\/08\/PowerShell-Processes-And-Piping\">last time<\/a>, I will now talk about writing re-usable scripts in PowerShell. Any command that we have executed at PowerShell command line can be dropped into a script file. I have lots of little PowerShell scripts for common tasks sitting in c:\\Utilities\\Scripts, which I include in my path. Let\u2019s say that I want to stop all running copies of Cassini (aka the Visual Studio Web Development Server aka WebDev.WebServer.exe).<\/p>\n<p>Stop-Process -name WebDev.WebServer.exe -ErrorAction SilentlyContinue<\/p>\n<p>This will terminate all running copies of the above-named process. ErrorAction is a common parameter for all PowerShell commands that tells PowerShell to ignore failures. (By default, Stop-Process would fail if no processes with that name were found.)<\/p>\n<p>We\u2019ve got our command. Now we want to turn it into a script so that we don\u2019t have to type it every time. Simply create a new text file with the above command text called \u201cStop-Cassini.ps1\u201d on your desktop using the text editor of your choice. (The script can be in any directory, but we\u2019ll put it on our desktop to start.) Let\u2019s execute the script by typing the following at the PowerShell prompt:<\/p>\n<p>Stop-Cassini<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" title=\"Current dirctory not in search path by default\" style=\"border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px\" height=\"153\" alt=\"Current dirctory not in search path by default\" src=\"\/wp-content\/uploads\/WindowsLiveWriter\/WritingScriptswithPowerShell_125DA\/image_5.png\" width=\"1029\" border=\"0\"> <\/p>\n<p>What just happened? Why can\u2019t PowerShell find my script? By default, PowerShell doesn\u2019t include the current directory in its search path, unlike cmd.exe. To run a script from the current directory, type the following:<\/p>\n<p>.\\Stop-Cassini<\/p>\n<p>Another option is to add the current directory to the search path by modifying Computer\u2026 Properties\u2026 Advanced\u2026 Environment Variables\u2026 Path. Or you can modify it for the current PowerShell session using:<\/p>\n<p>$env:Path += &#8216;.\\;&#8217;<\/p>\n<p>($env: provides access to environment variables in PowerShell. Try $env:ComputerName, $env:OS, $env:NUMBER_OF_PROCESSORS, etc.)<\/p>\n<p>You could also modify your PowerShell startup script, but we\u2019ll talk about that in a future instalment. Let\u2019s run our script again:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" title=\"ExecutionPolicy error\" style=\"border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px\" height=\"152\" alt=\"ExecutionPolicy error\" src=\"\/wp-content\/uploads\/WindowsLiveWriter\/WritingScriptswithPowerShell_125DA\/image_8.png\" width=\"1029\" border=\"0\"> <\/p>\n<p>No dice again. By default, PowerShell does not allow unsigned scripts to run. This is a good policy on servers, but is a royal pain on your own machine. That means that every time you create or edit a script, you have to sign it. This doesn\u2019t promote the use of quick scripts for simplifying development and administration tasks. So I turn off the requirement for script signing by running the following command from an elevated (aka Administrator) PowerShell prompt:<\/p>\n<p><strike>Set-ExecutionPolicy Unrestricted<\/strike><\/p>\n<p>Set-ExecutionPolicy RemoteSigned<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" title=\"Set-ExecutionPolicy succeeded\" style=\"border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px\" height=\"91\" alt=\"Set-ExecutionPolicy succeeded\" src=\"\/wp-content\/uploads\/WindowsLiveWriter\/WritingScriptswithPowerShell_125DA\/image_6d53deb0-11a4-4624-944f-7ecaf6919e50.png\" width=\"1029\" border=\"0\"><\/p>\n<p>If this command fails with an access denied error:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" title=\"Set-ExecutionPolicy failed\" style=\"border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px\" height=\"136\" alt=\"Set-ExecutionPolicy failed\" src=\"\/wp-content\/uploads\/WindowsLiveWriter\/WritingScriptswithPowerShell_125DA\/image_30df9cca-e3ce-4ad7-b30c-877eea9975c3.png\" width=\"1029\" border=\"0\"> <\/p>\n<p>then make sure that you launched a new PowerShell prompt via right-click Run as administrator\u2026<\/p>\n<\/p>\n<p>Third time is the charm\u2026<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" title=\"Success!\" style=\"border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px\" height=\"99\" alt=\"Success!\" src=\"\/wp-content\/uploads\/WindowsLiveWriter\/WritingScriptswithPowerShell_125DA\/image_20001279-4b07-4f31-9967-9988d229f348.png\" width=\"1029\" border=\"0\"> <\/p>\n<p>We are now able to write and use re-usable scripts in PowerShell. In my next instalment, we\u2019ll start pulling apart some more complicated scripts that simplify common developer tasks.<\/p>\n<p>UPDATE: As pointed out by Josh in the comments, setting your execution policy to RemoteSigned (rather than Unrestricted) is a better idea. Downloaded scripts will require you to unblock them (Right-click\u2026 Properties\u2026 Unblock or <a href=\"2004\/11\/09\/ZoneStripper-10-Released\">ZoneStripper<\/a> if you have a lot) before execution. Thanks for the correction.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Continuing on from last time, I will now talk about writing re-usable scripts in PowerShell. Any command that we have executed at PowerShell command line can be dropped into a script file. I have lots of little PowerShell scripts for common tasks sitting in c:\\Utilities\\Scripts, which I include in my path. Let\u2019s say that I [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16],"tags":[],"class_list":["post-47","post","type-post","status-publish","format-standard","hentry","category-powershell"],"_links":{"self":[{"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/posts\/47","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/comments?post=47"}],"version-history":[{"count":0,"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/posts\/47\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/media?parent=47"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/categories?post=47"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jameskovacs.com\/index.php\/wp-json\/wp\/v2\/tags?post=47"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}