Jekyll2019-08-16T19:52:26+00:00https://pcast01.github.io/feed.xmlDomain of AzraelA blog about coding mostly C#, Powershell, and javascript.Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/New website made with Gatsby.JS!2018-09-05T00:00:00+00:002018-09-05T00:00:00+00:00https://pcast01.github.io/New-Website-made-with-Gatsby<p>September 05, 2018</p>
<p>Please check out my new site made with Gatsby JS. Let me know what you think about it.</p>
<p>It’s at <a href="https://paulbcastillo.me">https://paulbcastillo.me</a>.</p>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/Avengers: Infinity War Trivia2018-04-26T00:00:00+00:002018-04-26T00:00:00+00:00https://pcast01.github.io/Avengers-Infinity-War-Trivia<p>April 26, 2018</p>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<script type="text/javascript">
function toggle_visibility(id, elem) {
var e = document.getElementById(id);
if(e.style.display == 'block') {
e.style.display = 'none';
elem.style.display = 'block'
} else {
e.style.display = 'block';
elem.style.display = 'none'
}
console.log(elem);
}
function toggleAll(){
var icon = document.getElementById('iconAll');
var all = $('.icon.fa-toggle-off:first');
if(all == 'undefined' || all.length === 0){
all = $('.icon.fa-toggle-on:first');
}
if(all.text() === "Show"){
all.text("Hide");
all.removeClass("fa-toggle-off");
all.addClass("fa-toggle-on");
$('a:contains("Click here")').hide();
for(x=0; x<9; x++){
var elem = document.getElementById(x);
if(elem != null){
elem.style.display = 'block';
}
}
} else {
all.text("Show");
all.removeClass("fa-toggle-on");
all.addClass("fa-toggle-off");
$('a:contains("Click here")').show()
for(x=0; x<9; x++){
var elem = document.getElementById(x);
if(elem != null){
elem.style.display = 'none';
}
}
}
}
</script>
<style>
.icon::before {
display: inline;
margin-right: .5em;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
transform: translate(0, 0);
}
</style>
<p><a href="#" onclick="toggleAll();return false;" class="icon fa-toggle-off">Show</a><br /></p>
<ol>
<li>
<div>The <a href="http://marvelcinematicuniverse.wikia.com/wiki/Collector" target="_blank">Collector</a> is a mysterious hoarder of rare artifacts, plants and one or two easter eggs. Which Marvel character does he have in his vault?<br /><i class="arrow-alt-circle-right"></i><a href="#" onclick="toggle_visibility('1',this);return false;">Click here for answer</a><div id="1" style="display: none;background-color: lightblue;"><a href="http://marvel.com/universe/Howard_the_Duck" target="_blank">Howard the Duck</a></div></div>
</li>
<li>
<div><a href="http://marvel.com/universe/Wakanda" target="_blank">Wakanda</a> is the advanced nation in the heart of Africa and <a href="http://marvel.com/universe/Black_Panther" target="_blank">Black Panther’s</a> homeland. What’s the material that’s helped Wakanda become so tech savvy?<br /><a href="#" onclick="toggle_visibility('2',this);return false;">Click here for answer</a><div id="2" style="display: none;background-color: lightblue;"><a href="http://marvelcinematicuniverse.wikia.com/wiki/Vibranium" target="_blank">Vibranium</a></div></div>
</li>
<li>
<div>What are the names of each of <a href="http://marvelcinematicuniverse.wikia.com/wiki/Infinity_Stones" target="_blank">six Infinity Stones</a>, and where are they now?<br /><a href="#" onclick="toggle_visibility(3,this);return false;">Click here for answer</a><div id="3" style="display: none;background-color: lightblue;"><b style="color:purple;">Soul</b> - unknown, <b style="color: green;">Space</b> - <a href="http://marvel.com/universe/Loki" target="_blank">Loki</a> has it, <b style="color: red;">Mind</b> - on <a href="http://marvel.com/universe/Vision" target="_blank">Vision's</a> head, <b style="color: yellow;">Reality</b> - The Collector has it, <b style="color: green;">Power</b> - protected by the <a href="http://marvel.com/universe/Nova_Corps" target="_blank">Nova Corps</a>, <b style="color: blue;">Time</b> - <a href="http://marvel.com/universe/Doctor_Strange_(Stephen_Strange)" target="_blank">Dr. Strange</a> has it in a necklace</div></div>
</li>
<li>
<div>How many marvel movies are there before Avengers: Infinity War?<br /><a href="#" onclick="toggle_visibility('4',this);return false;">Click here for answer</a><div id="4" style="display: none;background-color: lightblue;">18 movies.</div></div>
</li>
<li>
<div>Who is Gamora's adopted father?<br /><a href="#" onclick="toggle_visibility('5',this);return false;">Click here for answer</a><div id="5" style="display: none;background-color: lightblue;"><a href="http://marvel.com/universe/Thanos" target="_blank">Thanos</a>.</div></div>
</li>
<li>
<div>What is the name of <a href="http://marvel.com/universe/Spider-Man_(Peter_Parker)" target="_blank">Spiderman's</a> new suit in Avengers: Infinity War?<br /><a href="#" onclick="toggle_visibility('6',this);return false;">Click here for answer</a><div id="6" style="display: none;background-color: lightblue;">Iron Spider.</div></div>
</li>
<li>
<div>Avengers: Infinity War, marks how many years Marvel Studios has created the MCU(Marvel Cinematic Universe)?<br /><a href="#" onclick="toggle_visibility('7',this);return false;">Click here for answer</a><div id="7" style="display: none;background-color: lightblue;">10.</div></div>
</li>
<li>
<div>How many comic book characters are confirmed to appear in Avengers: Infinity War?<br /><a href="#" onclick="toggle_visibility('8',this);return false;">Click here for answer</a><div id="8" style="display: none;background-color: lightblue;">76</div></div>
</li>
</ol>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/Problem solving JavaScript’s Reduce function - just one of many use cases to utilize Reduce2018-02-26T00:00:00+00:002018-02-26T00:00:00+00:00https://pcast01.github.io/Problem-solving-JavaScripts-Reduce-function<p>February 26, 2018</p>
<p>Problem: Use one array and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">.reduce() function</a>.</p>
<p>Rules:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>* Return an object where each property is the name of the an ice cream flavor and each value is an integer that is the total count of that flavor.
* Store the returned data in a new iceCreamTotals variable.
</code></pre></div></div>
<h3 id="data">Data</h3>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">data</span> <span class="o">=</span> <span class="p">[</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="s1">'Superman'</span><span class="p">,</span> <span class="na">favoriteIceCreams</span><span class="p">:</span> <span class="p">[</span><span class="s1">'Strawberry'</span><span class="p">,</span> <span class="s1">'Vanilla'</span><span class="p">,</span> <span class="s1">'Chocolate'</span><span class="p">,</span> <span class="s1">'Cookies & Cream'</span><span class="p">]</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="s1">'Batman'</span><span class="p">,</span> <span class="na">favoriteIceCreams</span><span class="p">:</span> <span class="p">[</span><span class="s1">'Cookies & Cream'</span><span class="p">,</span> <span class="s1">'Mint Chocolate Chip'</span><span class="p">,</span> <span class="s1">'Chocolate'</span><span class="p">,</span> <span class="s1">'Vanilla'</span><span class="p">]</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="s1">'Flash'</span><span class="p">,</span> <span class="na">favoriteIceCreams</span><span class="p">:</span> <span class="p">[</span><span class="s1">'Chocolate'</span><span class="p">,</span> <span class="s1">'Rocky Road'</span><span class="p">,</span> <span class="s1">'Pistachio'</span><span class="p">,</span> <span class="s1">'Banana'</span><span class="p">]</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="s1">'Aquaman'</span><span class="p">,</span> <span class="na">favoriteIceCreams</span><span class="p">:</span> <span class="p">[</span><span class="s1">'Vanilla'</span><span class="p">,</span> <span class="s1">'Chocolate'</span><span class="p">,</span> <span class="s1">'Mint Chocolate Chip'</span><span class="p">]</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="s1">'Green Lantern'</span><span class="p">,</span> <span class="na">favoriteIceCreams</span><span class="p">:</span> <span class="p">[</span><span class="s1">'Vanilla'</span><span class="p">,</span> <span class="s1">'French Vanilla'</span><span class="p">,</span> <span class="s1">'Vanilla Bean'</span><span class="p">,</span> <span class="s1">'Strawberry'</span><span class="p">]</span> <span class="p">},</span>
<span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="s1">'Robin'</span><span class="p">,</span> <span class="na">favoriteIceCreams</span><span class="p">:</span> <span class="p">[</span><span class="s1">'Strawberry'</span><span class="p">,</span> <span class="s1">'Chocolate'</span><span class="p">,</span> <span class="s1">'Mint Chocolate Chip'</span><span class="p">]</span> <span class="p">}</span>
<span class="p">];</span>
</code></pre></div></div>
<h2 id="solution">Solution</h2>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">iceCreamTotals</span> <span class="o">=</span> <span class="nx">data</span><span class="p">.</span><span class="nx">reduce</span><span class="p">((</span><span class="nx">totals</span><span class="p">,</span> <span class="nx">superhero</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">superhero</span><span class="p">.</span><span class="nx">favoriteIceCreams</span><span class="p">.</span><span class="nx">map</span><span class="p">((</span><span class="nx">iceCreamType</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">totals</span><span class="p">[</span><span class="nx">iceCreamType</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="nx">totals</span><span class="p">[</span><span class="nx">iceCreamType</span><span class="p">]</span> <span class="o">||</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">return</span> <span class="nx">iceCreamType</span><span class="p">;</span>
<span class="p">});</span>
<span class="k">return</span> <span class="nx">totals</span><span class="p">;</span>
<span class="p">},</span> <span class="p">{});</span>
</code></pre></div></div>
<p>How did I arrive at this solution?! I will elaborate below.</p>
<p>So I used <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla">ES6(ECMAScript 6)</a> reduce function which is a dip into <a href="https://en.wikipedia.org/wiki/Functional_programming">Functional Programming</a> which I have found to be great to work with and expanded my mind coming from a <a href="https://en.wikipedia.org/wiki/Procedural_programming">Procedural Programming</a> background in programming. Functional Programming is unique and to wrap your brain around is difficult for me. So I came across the 3 functional methods: <a href="https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464">reduce, map and filter</a> and this helped out to get this problem solved. I have learned so much and I am so grateful to have not given up on javascript because I really thought it was just a pain and a necessary evil in the past.</p>
<h2 id="looking-for-help">Looking for help</h2>
<p>So naturally, I googled some ways to try to solve this problem and I came across this web page: <a href="https://medium.freecodecamp.org/reduce-f47a7da511a9">How JavaScript’s Reduce method works, when to use it, and some of the cool things it can do</a> and it was a life saver in coming up with my solution. My eyes were opened to the many uses of the Reduce function.</p>
<p>Here is the code:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">fruitBasket</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'banana'</span><span class="p">,</span> <span class="s1">'cherry'</span><span class="p">,</span> <span class="s1">'orange'</span><span class="p">,</span> <span class="s1">'apple'</span><span class="p">,</span> <span class="s1">'cherry'</span><span class="p">,</span> <span class="s1">'orange'</span><span class="p">,</span> <span class="s1">'apple'</span><span class="p">,</span> <span class="s1">'banana'</span><span class="p">,</span> <span class="s1">'cherry'</span><span class="p">,</span> <span class="s1">'orange'</span><span class="p">,</span> <span class="s1">'fig'</span> <span class="p">];</span>
<span class="kd">const</span> <span class="nx">count</span> <span class="o">=</span> <span class="nx">fruitBasket</span><span class="p">.</span><span class="nx">reduce</span><span class="p">(</span> <span class="p">(</span><span class="nx">tally</span><span class="p">,</span> <span class="nx">fruit</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">tally</span><span class="p">[</span><span class="nx">fruit</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="nx">tally</span><span class="p">[</span><span class="nx">fruit</span><span class="p">]</span> <span class="o">||</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span> <span class="p">;</span>
<span class="k">return</span> <span class="nx">tally</span><span class="p">;</span>
<span class="p">}</span> <span class="p">,</span> <span class="p">{})</span>
<span class="nx">count</span> <span class="c1">// { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }</span>
</code></pre></div></div>
<p>This is perfect for my solution since it brings back a single object and it also creates the property names along with the integer values.</p>
<p>The way this code works has a couple of things I didn’t know about. The main one was that the Reduce function has an optional argument that it takes and its an optional value that is the initial value of what you are accumulating.</p>
<p>Initial Value</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">,</span> <span class="p">{})</span>
</code></pre></div></div>
<p>The last thing I didn’t know about was the part of how it accumulates the tally.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">tally</span><span class="p">[</span><span class="nx">fruit</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="nx">tally</span><span class="p">[</span><span class="nx">fruit</span><span class="p">]</span> <span class="o">||</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span> <span class="p">;</span>
</code></pre></div></div>
<p>So breaking it down it made sense to me. So stepping through the first value(banana) in the <code class="highlighter-rouge">fruitbasket</code>,
if <code class="highlighter-rouge">tally[Banana]</code> exists then take its value (which is zero at the moment) and add 1 to it. Skip ahead to the 2nd to last item in the array. Now <code class="highlighter-rouge">tally[Banana]</code> is equal to 1 and since it does exist then add 1 + 1 and now <code class="highlighter-rouge">tally[Banana]</code> is equal to 2. If you follow this logic then you can see how the reduce function was used to get the totals in the tally object.</p>
<p>So my problem was that I had an object that had an array inside of each property. So in order to stay inside the rules of the problem I had to get the tally of the array inside of the object using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">.map function</a>.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">superhero</span><span class="p">.</span><span class="nx">favoriteIceCreams</span><span class="p">.</span><span class="nx">map</span><span class="p">((</span><span class="nx">iceCreamType</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="nx">totals</span><span class="p">[</span><span class="nx">iceCreamType</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="nx">totals</span><span class="p">[</span><span class="nx">iceCreamType</span><span class="p">]</span> <span class="o">||</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span>
<span class="k">return</span> <span class="nx">iceCreamType</span><span class="p">;</span>
<span class="p">});</span>
</code></pre></div></div>
<p>the key to this working was totals Accumulator variable. I had to reference a variable outside of the map function and it works because that object lives inside the reduce function. Normally the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">.map function</a> returns a new array but I don’t need that object I just needed to iterate through every item in the array. So all said and done I just return totals and that is all that is needed.</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">iceCreamTotals</span> <span class="o">=</span> <span class="nx">data</span><span class="p">.</span><span class="nx">reduce</span><span class="p">((</span><span class="nx">totals</span><span class="p">,</span> <span class="nx">superhero</span><span class="p">)</span> <span class="o">=></span> <span class="p">{</span>
<span class="p">...</span>
<span class="k">return</span> <span class="nx">totals</span><span class="p">;</span>
<span class="p">},</span> <span class="p">{});</span>
</code></pre></div></div>
<p>I was happy knowing that I could solve this problem and hope it will help someone else who might be struggling with a similiar problem.</p>
<h3 id="recommended-links">Recommended links:</h3>
<ul>
<li><a href="https://code.visualstudio.com/">VSCode</a> for coding in javascript!</li>
<li><a href="https://www.google.com/chrome/">Google Chrome</a> quick javascript debugging.</li>
<li><a href="https://github.com/lukehoban/es6features">ES6 features</a> for a breakdown of all the ES6 features.</li>
<li><a href="http://wesbos.com/es6-for-everyone/">ES6 for everyone!</a> from Wes Bos.</li>
<li><a href="https://hackernoon.com/understanding-map-filter-and-reduce-in-javascript-5df1c7eee464">Understanding map, filter and reduce in Javascript</a> on HackerNoon.com.</li>
<li><a href="https://developers.google.com/web/tools/chrome-devtools/javascript/">Get Started with Debugging JavaScript in Chrome DevTools</a> for debugging in Chrome.</li>
</ul>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/How to create your own Google Sheets Custom Function2017-06-29T00:00:00+00:002017-06-29T00:00:00+00:00https://pcast01.github.io/Javascript-GoogleSheets-CustomFunction<p>June 29, 2017</p>
<h2 id="how-to-create-a-custom-function-in-google-sheets">How to create a custom Function in Google Sheets</h2>
<blockquote>
<p><em>Why would you create a custom Function in Google Sheets?!</em></p>
</blockquote>
<p>When you create a custom function you have full control over the input and output of what you want to create. Its a powerful feature that is exposed for you to use.</p>
<h3 id="custom-functions-basic-requirements">Custom Functions basic requirements</h3>
<hr />
<h4 id="naming">Naming</h4>
<ol>
<li>The name cannot be a name of an already defined Built-in Function like <code class="highlighter-rouge">=Sum()</code> for example.</li>
<li>The name cannot contain an underscore <code class="highlighter-rouge">_</code> at the end of the function because that is used in Google Apps Script.</li>
<li>The name of your custom function must be declared with this syntax: <code class="highlighter-rouge">function myFunction</code>, and cannot be declared as a <code class="highlighter-rouge">var myFunction</code></li>
</ol>
<h3 id="my-custom-function-combinestringsfirst-second">My Custom Function: COMBINESTRINGS(first, second)</h3>
<ul>
<li>The purpose of this function is to bring two columns together as one string and return that to the cell where you input the function.</li>
</ul>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/** Brings two columns of strings together.
*
* @param {string} First string.
* @param {string} Second string.
* @return both strings together.
* @customfunction
**/
function COMBINESTRINGS(first, second) {
return first + ' ' + second;
}
</code></pre></div></div>
<h3 id="start">Start</h3>
<ol>
<li>
<p>Create a Google Sheets file inside Google Drive.</p>
</li>
<li>
<p>Go to Tools -> Script Editor</p>
<p> <img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/scriptEditor.png" alt="ScriptEditor" /></p>
<p> Script Editor Window</p>
<p> <img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/defaultCodeWindow.png" alt="Default Code Window" /></p>
<p> Code window with the custom function.</p>
<p> <img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/codeFunction.png" alt="Function Code" /></p>
</li>
<li>
<p>Run the script.</p>
<p>To run the script in the window you would normally click the play button it would work but since this is a Custom Function it should be called from the sheet cells. The other way to test the function is to create another function and call this function with the parameters.</p>
<p>But since we haven’t run anything at all we have to run the script and we will prompted to name the project. So click the play button and this window will come up. When it does just name the project whatever you like.</p>
<p> <img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/EditProjName.png" alt="Function Code" /></p>
</li>
<li>
<p>Autocompletion</p>
<ul>
<li>
<p>If you commented your function correctly and the right syntax then you should see this.
<img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/combineStringsAutocompletion.png" alt="Function" /></p>
</li>
<li>
<p>Here is the sheet with the two strings and the function working in the sheet.</p>
</li>
</ul>
<p> <img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/example.png" alt="Function" /></p>
</li>
<li>
<p>Inputs - Arrays</p>
</li>
</ol>
<p>According this this google example you can also accept and array of objects or cells.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/**
* Multiplies the input value by 2.
*
* @param {number} input The value or range of cells to multiply.
* @return The input multiplied by 2.
* @customfunction
*/
function DOUBLE(input) {
if (input.map) { // Test whether input is an array.
return input.map(DOUBLE); // Recurse over array if so.
} else {
return input * 2;
}
}
</code></pre></div></div>
<p>If you run this with just one cell, say A4 which has the value 2 in it. <code class="highlighter-rouge">=DOUBLE(A4)</code> Then it will return 4. But what if you select a range of cells?…</p>
<p>We will select 3 cells as the input: <code class="highlighter-rouge">=DOUBLE(A4:C4)</code> and the cells are 2, 4, and 5. It returns 4, 8 and 10 respectively.</p>
<p>To understand this function lets step thru each line.</p>
<p><code class="highlighter-rouge">if (input.map) {</code> - this line takes the input and says “does the map function exist?” If so then th object input is an Array, then return a call to THIS same function and run DOUBLE on every element in the array. So 2 runs thru DOUBLE and its not an array and so it runs the else part <code class="highlighter-rouge">return input * 2</code> so it returns 2 * 2 which is 4. Then it does the same for 4 and 5 until there are no more elements in the array.</p>
<p><img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/DOUBLE_array_final.png" alt="DOUBLE ARRAY" /></p>
<p>This feature in Google Functions is extremely powerful because not only can you use a function with one parameter you can use an array. Lets look at some other examples.</p>
<h2 id="get-web-url-links">Get Web URL Links</h2>
<p>I created a function to get all the links from any website URL.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/**
* Gets all links from web page
*
* @param {string} input The website url
* @return The links in a page
* @customfunction
*/
function getWebLinks(url) {
var response = UrlFetchApp.fetch(url);
var content = response.getContentText();
var linkUrls = content.match(/href="(.*?)"/g).toString();
var arrayLinks = linkUrls.split(',');
return arrayLinks;
}
</code></pre></div></div>
<p>I use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" target="_blank">Regular Expressions</a> to find all the links in the document on this line: <code class="highlighter-rouge">var linkUrls = content.match(/href="(.*?)"/g).toString();</code> and then I use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" target="_blank">array function split()</a> to separate every text between commas into and array called arrayLinks. Then I return the array and all the links populate one row at a time on the sheet.</p>
<p><em>* Tip: I use <a href="http://regexr.com/" target="_blank">RegExr.com</a> to help create my Regular expressions because its a quick resource to help test out different regular expressions.</em></p>
<p>To test the function I created, I create two more functions. One called test() and the other called LogLink();</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>function LogLink(input){
return Logger.log(input);
}
function test() {
var url = getWebLinks('https://developers.google.com/apps-script/guides/sheets/functions#optimization');
url.map(LogLink);
}
</code></pre></div></div>
<p>LogLink takes in input and then uses the built-in <a href="https://developers.google.com/apps-script/reference/base/logger#logdata" target="_blank">Logger.log function</a> which prints to the log found in the code editor window from the menu View -> View Logs(ctrl+Enter).</p>
<p>And test function just runs the getWebLinks Function outside of the sheets window. So I select the function from the top menu dropdown.</p>
<p><img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/function_dropdown.png" alt="Function Dropdown" /></p>
<p>and then I click the Play button.</p>
<p>After the script runs(you can see a pop that says script running and then disappears) you can go int the Logs and view this:</p>
<p><img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/logsWindow.png" alt="Log Window" /></p>
<p>So I get this working and then I put it in the sheets window.</p>
<p><img src="https://pcast01.github.io/assets/images/GoogleSheetsCustomFunction/getWebLinksPreview.png" alt="WebLinksSheet" /></p>
<h3 id="apps-script-services">Apps Script Services</h3>
<p>Custom functions can use these services offered by Google. Some are easier to connect to than others but this is the list from <a href="https://developers.google.com/apps-script/guides/sheets/functions#using_apps_script_services" target="blank">Google</a> that they provide.</p>
<table>
<thead>
<tr>
<th style="text-align: center">Supported Services</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center">Cache</td>
</tr>
<tr>
<td style="text-align: center">HTML</td>
</tr>
<tr>
<td style="text-align: center">JDBC</td>
</tr>
<tr>
<td style="text-align: center">Lock</td>
</tr>
<tr>
<td style="text-align: center">Maps</td>
</tr>
<tr>
<td style="text-align: center">Properties</td>
</tr>
<tr>
<td style="text-align: center">Spreadsheet</td>
</tr>
<tr>
<td style="text-align: center">URL Fetch</td>
</tr>
<tr>
<td style="text-align: center">Utilities</td>
</tr>
<tr>
<td style="text-align: center">XML</td>
</tr>
</tbody>
</table>
<h3 id="summary">Summary</h3>
<p>Creating a custom function will give you flexibility to create whatever you want in Google Sheets and its a powerful tool to help you customize your use of javascript and all its power.</p>
<ul>
<li>If you have any questions feel free to comment below or even contact me from any links on the sidebar.</li>
</ul>
<h4 id="references">References</h4>
<ul>
<li>Gist script
<script src="https://gist.github.com/pcast01/58177141dd9aaef6cbc58aa1790d9401.js"></script></li>
</ul>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/How I learn JavaScript2017-06-26T00:00:00+00:002017-06-26T00:00:00+00:00https://pcast01.github.io/Javascript-Learning<p>June 26, 2017</p>
<h1 id="how-i-am-learning-javascript">How I am learning <a href="https://en.wikipedia.org/wiki/JavaScript" target="_blank">JavaScript;</a></h1>
<p>Lately I have been trying to learn all I can about JavaScript. Coming from a background of .Net it was a little troublesome at first because lets face it JavaScript was a pain when I started learning it and it was a chore at best. Within the past year I have begun embracing it and all its odd complexities. Now I am just fascinated with its flexibility and popularity. Here are some of the ways I am learning it.</p>
<h2 id="learning-by-solving-real-world-problems">Learning by solving real-world problems;</h2>
<p>I was trying to decide how I can get some real-world <a href="https://en.wikipedia.org/wiki/JavaScript" target="_blank">JavaScript</a> code out there when I came across <a href="https://www.fiverr.com/" target="_blank">Fiverr.com</a>. I want to eventually create a side business and this was my first real attempt to “get out there” and do some work. So I decided to go full in on Fiverr and I did for a few months then I had to stop using it because of personal reasons. I learned so much by working on small tasks in Google apps like Google Sheets, which uses JavaScript as its scripting language.</p>
<ul>
<li><a href="https://developers.google.com/apps-script/articles/" target="_blank">Google Sheets Tutorials</a> - This is Google’s site for learning scripting in Sheets. Great resource.</li>
<li><a href="http://www.mousewhisperer.co.uk/drivebunny/" target="_blank">Drive Bunny</a> - I used this site a lot when I was working consistently in Google Sheets and needed some quick answers.</li>
<li><a href="https://www.labnol.org/" target="_blank">Digital Inspiration by Amit Agarwal</a> - This guy is a genius and has a lot of great work out there to share with the world, go here if you want answers! He has built lots of useful tools to use all over.</li>
</ul>
<h2 id="tutorialsvideos">Tutorials/Videos;</h2>
<ul>
<li><a href="https://frontendmasters.com/" target="_blank">Advanced Javascript - Kyle Simpson</a> - I enjoyed this video series by <a href="https://github.com/getify" target="_blank">Kyle</a> and I highly recommend watching it.</li>
<li><a href="https://www.rithmschool.com/courses#jsfundamentals" target="_blank">Javascript Fundamentals - Rithm School</a>- This is a great source to learn from as they have lots of videos and examples to learn from. They also have a github repo setup with questions and answers to go thru.</li>
<li><a href="https://watchandcode.com/p/practical-javascript" target="_blank">Practical Javascript by Gordon Zhu</a> - I love <a href="https://github.com/gordonmzhu" target="_blank">Gordon’s</a> teaching style as he relays all his information in an easy to understand way. I learned a lot by following along with him on learning practical JavaScript. I really like his workflow as well, he goes thru many iterations and refactoring of his code.</li>
<li><a href="https://javascript30.com/" target="_blank">JavaScript 30 - Wes Bos</a> - This free course is a gold mine of great tutorials and real-world examples. Filled with lots of <a href="https://stackoverflow.com/questions/3934826/what-do-people-mean-by-dom-manipulation-and-how-would-i-do-that" target="_blank">DOM manipulation</a> and <a href="https://github.com/lukehoban/es6features" target="_blank">ES6</a> techniques. Wes is a great teacher and showed me a lot of ways to constructively look at my coding.</li>
<li><a href="https://youtu.be/eJV-hqQGZXU" target="_blank">Scott Hanselman’s JavaScript & the Rise of the Virtual Machine</a> - This is the video(which I was there live) that really opened my eyes to the possibilities of JavaScript and also the power that it has. Highly Recommend watching this video if you have spare time.</li>
<li><a href="https://devchat.tv/js-jabber" target="_blank">JavaScript Jabber </a>- I listen to this podcast every week and its essential to get the latest and greatest js.</li>
<li><a href="https://arkmont.com/functional-programming-in-javascript" target="_blank">Functional Programming in JavaScript - Mattias Johansson</a> - I loved this course as it was my first attempt to learn some functional programming. Mattias is silly and has a great sense of humor in teaching his style.</li>
</ul>
<h2 id="blogging-solutionsideastutorials">Blogging solutions/ideas/tutorials;</h2>
<p>I am going to be blogging about all things that I have learned on my journey and this is helping me to realize that it can only help me on my own journey of learning JavaScript. So I will be posting more on here to help anyone out there like all these other people helped me work thru my problems. Giving back is essential to learn and contribute to the community.</p>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/PowerShell with Microsoft Excel Macro2017-01-17T00:00:00+00:002017-01-17T00:00:00+00:00https://pcast01.github.io/Start-Excel-Macro-From-PowerShell<p>January 17, 2017</p>
<h1 id="create-powershell-script-to-open-and-run-macro-in-excel">Create PowerShell Script to open and run Macro in Excel</h1>
<p>Below is an example of how to use PowerShell to automatically run an Excel macro.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Function </span>RunExcelMacro<span class="o">()</span> <span class="o">{</span>
<span class="c1"># Open Excel file</span>
<span class="nv">$excel</span> <span class="o">=</span> <span class="nb">new-object</span> -comobject excel.application
<span class="nv">$filePath</span> <span class="o">=</span> <span class="s2">"C:\PowershellSheet.xlsm"</span>
<span class="nv">$workbook</span> <span class="o">=</span> <span class="nv">$excel</span>.Workbooks.Open<span class="o">(</span><span class="nv">$FilePath</span><span class="o">)</span>
<span class="nv">$excel</span>.Visible <span class="o">=</span> <span class="nv">$true</span>
<span class="nv">$worksheet</span> <span class="o">=</span> <span class="nv">$workbook</span>.worksheets.item<span class="o">(</span>1<span class="o">)</span>
<span class="nb">Write-Host</span> <span class="s2">"Running macro in excel to scrub data."</span>
<span class="nv">$excel</span>.Run<span class="o">(</span><span class="s2">"PowershellMacro"</span><span class="o">)</span>
<span class="nv">$workbook</span>.save<span class="o">()</span>
<span class="nv">$workbook</span>.close<span class="o">()</span>
<span class="nv">$excel</span>.quit<span class="o">()</span>
<span class="nb">Write-Host</span> <span class="s2">"Closed Excel"</span>
<span class="o">}</span>
</code></pre></div></div>
<p>This code calls creates a COM Excel object and then opens an Excel Macro called “PowershellMacro”. After it executes the macro then we explicitly quit excel and the process closes.</p>
<p>Here are some good references on how to use Excel inside of PowerShell.</p>
<p>Here is the xlsm file: <a href="https://pcast01.github.io/assets/docs/PowershellSheet.xlsm" target="_blank">PowershellSheet.xlsm</a></p>
<p>Here is the ps1 file: <a href="https://pcast01.github.io/assets/docs/PowershellExcelMacro.ps1" target="_blank">PowershellExcelMacro.ps1</a></p>
<ul>
<li><a href="https://blogs.technet.microsoft.com/heyscriptingguy/2006/09/08/how-can-i-use-windows-powershell-to-automate-microsoft-excel/" target="_blank">Scripting guy</a></li>
<li><a href="http://ramblingcookiemonster.github.io/PSExcel-Intro/" target="_blank">Rambling Cookie Monster</a></li>
<li><a href="https://posh2scripting.wordpress.com/2013/07/31/automating-excel-spreadsheets-with-powershell/" target="_blank">Posh2Scripting</a></li>
</ul>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/Updated-Custom Windows File and Pattern Search in PowerShell script2017-01-08T00:00:00+00:002017-01-08T00:00:00+00:00https://pcast01.github.io/Updated-Custom-Windows-Search-Files-Powershell<p>January 08, 2017</p>
<h1 id="custom-windows-search">Custom Windows Search</h1>
<p>I decided that I needed to start using resources around me better to write better PowerShell. So I posted the code on the <a href="https://www.reddit.com/r/PowerShell/">PowerShell Sub-Reddit</a> and I got some great advice from user <a href="https://www.reddit.com/user/Lee_Dailey">Lee_Dailey</a> on my post - <a href="https://www.reddit.com/r/PowerShell/comments/5l6nux/custom_windows_file_and_pattern_search_in/">Custom Windows File and Pattern Search in PowerShell script</a>.</p>
<p>Here is the updated full script:
<script src="https://gist.github.com/6f3fd24642748c2f47f15ed8c5bc39b9.js"> </script></p>
<h2 id="breakdown-of-script">Breakdown of script</h2>
<p>I modified the first helper function for formatting the size of the file to be a cleaner function that uses a <code class="highlighter-rouge">switch</code> statement instead of nested ifs and also I use the <a href="http://ss64.com/ps/syntax-f-operator.html">format operator</a> in PowerShell instead of .Net framework calls.</p>
<p>Here is the original function.
<strong>Format-FileSize</strong> function takes one integer that is the Length property of a file and formats it according to its size. i.e. <em>1KB, 1MB…</em></p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Function </span>Format-FileSize<span class="o">()</span> <span class="o">{</span>
<span class="k">Param</span> <span class="o">([</span><span class="kt">int</span><span class="o">]</span><span class="nv">$size</span><span class="o">)</span>
<span class="k">If</span> <span class="o">(</span><span class="nv">$size</span> -gt 1TB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} TB"</span>, <span class="nv">$size</span> / 1TB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 1GB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} GB"</span>, <span class="nv">$size</span> / 1GB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 1MB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} MB"</span>, <span class="nv">$size</span> / 1MB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 1KB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} KB"</span>, <span class="nv">$size</span> / 1KB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 0<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} B"</span>, <span class="nv">$size</span><span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -eq 0<span class="o">)</span> <span class="o">{</span><span class="s2">"0 MB"</span><span class="o">}</span>
<span class="k">Else</span> <span class="o">{</span><span class="s2">""</span><span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The new Format-FileSize functions is more functional for PowerShell and cuts down the use of .Net Framework which I have found out in this process is a crutch of mine to always want to tap into my C# skills and apply it in PowerShell. First off, <a href="https://www.reddit.com/user/Lee_Dailey">Lee_Dailey</a> pointed out that using an int variable type might have an error for files with big sizes so I changed the <code class="highlighter-rouge">[Int]</code> to <code class="highlighter-rouge">[Int64]</code>
He pointed out that its best to use a <code class="highlighter-rouge">Switch</code> Statement instead of nested Ifs and he was right.</p>
<p>Also instead of using</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[string]::Format("{0:0.00} MB", $size / 1MB)
</code></pre></div></div>
<p>its better to use the <a href="http://ss64.com/ps/syntax-f-operator.html">PowerShell format operator</a>:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>"{0:0.00} MB" -f ($size / 1MB)
</code></pre></div></div>
<p>The new function Format-FileSize:</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">Function </span>Format-FileSize <span class="o">{</span>
<span class="k">Param</span> <span class="o">([</span>int64]<span class="nv">$size</span><span class="o">)</span>
<span class="c1"># Based on File.Length in bytes return appropriate size</span>
<span class="k">switch</span><span class="o">(</span><span class="nv">$size</span><span class="o">)</span>
<span class="o">{</span>
<span class="o">{</span> <span class="nv">$_</span> -gt 1TB <span class="o">}</span>
<span class="o">{</span><span class="s2">"{0:0.00} TB"</span> -f <span class="o">(</span><span class="nv">$size</span> / 1TB<span class="o">)</span>; <span class="k">break</span><span class="o">}</span>
<span class="o">{</span> <span class="nv">$_</span> -gt 1GB <span class="o">}</span>
<span class="o">{</span><span class="s2">"{0:0.00} GB"</span> -f <span class="o">(</span><span class="nv">$size</span> / 1GB<span class="o">)</span>; <span class="k">break</span><span class="o">}</span>
<span class="o">{</span> <span class="nv">$_</span> -gt 1MB <span class="o">}</span>
<span class="o">{</span><span class="s2">"{0:0.00} MB"</span> -f <span class="o">(</span><span class="nv">$size</span> / 1MB<span class="o">)</span>; <span class="k">break</span><span class="o">}</span>
<span class="o">{</span> <span class="nv">$_</span> -gt 1KB <span class="o">}</span>
<span class="o">{</span><span class="s2">"{0:0.00} KB"</span> -f <span class="o">(</span><span class="nv">$size</span> / 1KB<span class="o">)</span>; <span class="k">break</span><span class="o">}</span>
<span class="o">{</span> <span class="nv">$_</span> -gt 0 <span class="o">}</span>
<span class="o">{</span><span class="s2">"{0:0.00} B"</span> -f <span class="o">(</span><span class="nv">$size</span><span class="o">)</span>; <span class="k">break</span><span class="o">}</span>
<span class="o">{</span> <span class="nv">$_</span> -eq 0 <span class="o">}</span>
<span class="o">{</span><span class="s2">"0 KB"</span>; <span class="k">break</span><span class="o">}</span>
default
<span class="o">{</span> <span class="s2">"0 KB"</span> <span class="o">}</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<h2 id="header-of-the-script-menu">Header of the script menu</h2>
<p>This is the opening screen for the script which shows the PowerShell Version from the start and then I do a <code class="highlighter-rouge">Read-Host</code> to show this header for the script.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ver</span> <span class="o">=</span> <span class="nv">$psversiontable</span>.psversion
<span class="nb">Write-Host</span> <span class="s2">"PowerShell version: </span><span class="nv">$ver</span><span class="s2">"</span>
<span class="nb">Write-Host</span> <span class="s2">"Script Mission: takes a list of locations to search and looks at another "</span>
<span class="nb">Write-Host</span> <span class="s2">" list that has specific words to match and compilates a list"</span>
<span class="nb">Write-Host</span> <span class="s2">" with information about matches found in the filename."</span>
<span class="nb">Write-Host</span> <span class="s2">"---------------------------------------------------------------------"</span>
<span class="nb">Write-Host</span> <span class="s2">" Select Folder where Locations and Patterns text files are located when prompted"</span>
<span class="nv">$startScript</span> <span class="o">=</span> <span class="nb">Read-Host</span> -Prompt <span class="s1">'Hit enter to continue'</span>
</code></pre></div></div>
<p>Here is the <em>updated script menu</em>.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ver</span> <span class="o">=</span> <span class="nv">$psversiontable</span>.psversion
<span class="nb">Write-Host</span> <span class="s2">"PowerShell version: </span><span class="nv">$ver</span><span class="s2">"</span>
<span class="nb">Write-Host</span> <span class="s2">"Script Mission: Custom filename search that requires two text files, "</span>
<span class="nb">Write-Host</span> <span class="s2">" named locations.txt(path locations to search) and patterns.txt"</span>
<span class="nb">Write-Host</span> <span class="s2">" (specific word searches). Then creates small report called Results.txt file with findings."</span>
<span class="nb">Write-Host</span> <span class="s2">"----------------------------------------------------------------------------------------------------------"</span>
<span class="nb">Write-Host</span> <span class="s2">" Select Folder where Locations and Patterns text files are located when prompted"</span>
<span class="nv">$startScript</span> <span class="o">=</span> <span class="nb">Read-Host</span> -Prompt <span class="s1">'Hit enter to continue'</span>
</code></pre></div></div>
<h2 id="browse-for-folder-dialog-box">Browse for folder Dialog box</h2>
<p><img src="https://pcast01.github.io/assets/images/BrowseForFolder.png" alt="BrowseForFolder" /></p>
<p>The next part I found some code that will open the BrowseForFolder dialog windows that allows you to navigate to the folder
where the locations and patterns text files are located. Then it checks if both files exists if not then it exits the script.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$application</span> <span class="o">=</span> <span class="nb">New-Object</span> -ComObject Shell.Application
<span class="nv">$path</span> <span class="o">=</span> <span class="o">(</span><span class="nv">$application</span>.BrowseForFolder<span class="o">(</span>0, <span class="s1">'Select root folder of new WebSite'</span>, 0<span class="o">))</span>.Self.Path
<span class="k">if</span><span class="o">([</span><span class="kt">string</span><span class="o">]</span>::IsNullOrEmpty<span class="o">(</span><span class="nv">$path</span><span class="o">))</span>
<span class="o">{</span>
<span class="nb">Write-Host</span> <span class="s2">"Exiting script..."</span>
<span class="k">exit</span>
<span class="o">}</span>
<span class="nb">cd</span> <span class="nv">$path</span>
<span class="nv">$locPath</span> <span class="o">=</span> <span class="nv">$path</span> + <span class="s2">"\locations.txt"</span>
<span class="nv">$patternPath</span> <span class="o">=</span> <span class="nv">$path</span> + <span class="s2">"\patterns.txt"</span>
<span class="k">if</span><span class="o">(![</span>System.IO.File]::Exists<span class="o">(</span><span class="nv">$locPath</span><span class="o">)){</span>
<span class="nb">Write-Host</span> <span class="s2">"* Locations text file does not exist in </span><span class="nv">$path</span><span class="s2">. Exiting..."</span> -ForegroundColor Red
<span class="k">Exit</span>
<span class="o">}</span>
</code></pre></div></div>
<p><em>Updated part:</em> I changed this part of the code by separating some code by using a function, the first part of the code I kept but the <code class="highlighter-rouge">$path</code> variable I get at pass it to a newly created function called <code class="highlighter-rouge">Retrieve-FilesByPatternLocation</code>.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Run Search functions with path variable.</span>
Retrieve-FilesByPatternLocation -path <span class="nv">$path</span>
</code></pre></div></div>
<h2 id="the-major-part-of-the-script">The major part of the script</h2>
<p>The original setup of the 2 <code class="highlighter-rouge">foreach</code> loops were at best messy and not streamlined.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">foreach</span> <span class="o">(</span><span class="nv">$folder</span> <span class="k">in</span> <span class="nv">$folders</span><span class="o">)</span> <span class="o">{</span>
<span class="nv">$files</span> <span class="o">=</span> <span class="nb">gci</span> -Path <span class="nv">$folder</span> -Recurse <span class="k">*</span>.<span class="k">*</span>
<span class="nb">Write-Host</span> <span class="s2">"Searching folder: </span><span class="nv">$folder</span><span class="s2"> -------------------------"</span>
<span class="nv">$file</span> <span class="o">=</span> <span class="nv">$file</span> + <span class="s2">"********************************************************************</span><span class="se">`r`n</span><span class="s2">Searching folder: </span><span class="nv">$folder</span><span class="se">`r`n</span><span class="s2">********************************************************************</span><span class="se">`r`n</span><span class="s2">"</span>
<span class="k">foreach</span> <span class="o">(</span><span class="nv">$pattern</span> <span class="k">in</span> <span class="nv">$patterns</span><span class="o">)</span> <span class="o">{</span>
<span class="nv">$resultsFile</span> <span class="o">=</span> <span class="nb">Get-ChildItem</span> -Recurse -Force <span class="nv">$folder</span> -ErrorAction SilentlyContinue |
<span class="nb">Where</span>-Object <span class="o">{</span> <span class="o">(</span><span class="nv">$_</span>.PSIsContainer -eq <span class="nv">$false</span><span class="o">)</span> -and <span class="o">(</span> <span class="nv">$_</span>.Name -like <span class="s2">"*</span><span class="nv">$pattern</span><span class="s2">*"</span><span class="o">)</span> <span class="o">}</span> |
<span class="nb">Select-Object</span> @<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Folder"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.Directory<span class="o">}}</span>,@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"FileName"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.Name<span class="o">}}</span> ,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Size"</span>;<span class="nv">Expression</span><span class="o">={</span>Format-FileSize<span class="o">(</span><span class="nv">$_</span>.Length<span class="o">)}}</span>, @<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Last Modified Date"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.LastWriteTime<span class="o">}}</span>,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Owner"</span>;<span class="nv">Expression</span><span class="o">={(</span><span class="nb">Get-acl</span> <span class="nv">$_</span>.FullName<span class="o">)</span>.Owner<span class="o">}}</span> | <span class="nb">Format-Table</span> -AutoSize <span class="k">*</span> | <span class="nb">Out-String</span> -Width 4096
<span class="nv">$rNumbers</span> <span class="o">=</span> <span class="nb">Get-ChildItem</span> -Recurse -Force <span class="nv">$folder</span> -ErrorAction SilentlyContinue | <span class="nb">Where</span>-Object <span class="o">{</span> <span class="o">(</span><span class="nv">$_</span>.PSIsContainer -eq <span class="nv">$false</span><span class="o">)</span> -and <span class="o">(</span> <span class="nv">$_</span>.Name -like <span class="s2">"*</span><span class="nv">$pattern</span><span class="s2">*"</span><span class="o">)</span> <span class="o">}</span>
<span class="nv">$resultsFile</span>
<span class="nv">$rCount</span> <span class="o">=</span> <span class="nv">$rNumbers</span>.Count
<span class="nb">Write-Host</span> <span class="s2">"Count: </span><span class="nv">$rCount</span><span class="s2">"</span>
<span class="nv">$file</span> <span class="o">=</span> <span class="nv">$file</span> + <span class="s2">"=========== Searching for </span><span class="nv">$pattern</span><span class="s2"> ===========</span><span class="se">`r`n</span><span class="s2">**Number of Files found: </span><span class="nv">$rCount</span><span class="se">`r`n`r`n</span><span class="s2">"</span> + <span class="nv">$resultsFile</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The new <code class="highlighter-rouge">foreach</code> loops. Right away the readability is greatly improved. I changed the <code class="highlighter-rouge">$folders</code> variable to <code class="highlighter-rouge">$AllFolders</code> and the same with <code class="highlighter-rouge">$patterns</code> to <code class="highlighter-rouge">$AllPatterns</code>. I also now am not using aliases as I have learned are not the best practice to use, I since have thought that I should only be using aliases in my day to day PowerShell sessions. I reduced the number asterisks by using <code class="highlighter-rouge">("*" * 68)</code> I also put spaces between sets of code which I believe separates its nicely and is easy on the eyes.</p>
<p>This is the best part that benefited the most of this deep dive in my opinion. Before I got sloppy and was trying to get the script done fast as I was on a deadline. But because of this I ran <code class="highlighter-rouge">Get-ChildItem</code> twice and poor performance was had. Maybe not real bad since my script is small but I have seen a noticeable difference. I also didn’t do my homework when studying <code class="highlighter-rouge">Get-ChildItem</code> because if I did I would’ve known that there are two parameters that it takes that I was using after I piped the data. And those two are <code class="highlighter-rouge">-Folder</code> and <code class="highlighter-rouge">-Filter</code>. I was using <code class="highlighter-rouge">Where-Object { ($_.PSIsContainer -eq $false) -and ( $_.Name -like "*$pattern*")</code>. I also get the count of the files found before I pipe the results to the <code class="highlighter-rouge">Select-Object</code>.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Perform recurse filter search and get file count</span>
<span class="nv">$Results</span> <span class="o">=</span> <span class="nb">Get-ChildItem</span> -Recurse -Force <span class="nv">$folder</span> -ErrorAction SilentlyContinue -File -Filter <span class="s2">"*</span><span class="nv">$pattern</span><span class="s2">*"</span>
<span class="nv">$FilesCount</span> <span class="o">=</span> <span class="nv">$Results</span>.Count
</code></pre></div></div>
<p>Updated foreach code block</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">foreach</span> <span class="o">(</span><span class="nv">$folder</span> <span class="k">in</span> <span class="nv">$AllFolders</span><span class="o">)</span> <span class="o">{</span>
<span class="c1"># Write folder name to screen</span>
<span class="nb">Write-Host</span> <span class="s2">"Searching folder: </span><span class="nv">$folder</span><span class="s2"> -------------------------"</span>
<span class="nv">$Message</span> <span class="o">=</span> <span class="nv">$Message</span> + <span class="o">(</span><span class="s2">"*"</span> <span class="k">*</span> 68<span class="o">)</span> + <span class="s2">"</span><span class="se">`r`n</span><span class="s2">Searching folder: </span><span class="nv">$folder</span><span class="se">`r`n</span><span class="s2">"</span> + <span class="o">(</span><span class="s2">"*"</span> <span class="k">*</span> 68<span class="o">)</span> +<span class="s2">"</span><span class="se">`r`n</span><span class="s2">"</span>
<span class="c1"># look for all file names with all Patterns</span>
<span class="k">foreach</span> <span class="o">(</span><span class="nv">$pattern</span> <span class="k">in</span> <span class="nv">$AllPatterns</span><span class="o">)</span> <span class="o">{</span>
<span class="c1"># Perform recurse filter search and get file count</span>
<span class="nv">$Results</span> <span class="o">=</span> <span class="nb">Get-ChildItem</span> -Recurse -Force <span class="nv">$folder</span> -ErrorAction SilentlyContinue -File -Filter <span class="s2">"*</span><span class="nv">$pattern</span><span class="s2">*"</span>
<span class="nv">$FilesCount</span> <span class="o">=</span> <span class="nv">$Results</span>.Count
<span class="c1"># Get file attributes and format them</span>
<span class="nv">$Results</span> <span class="o">=</span> <span class="nv">$Results</span> |
<span class="nb">Select-Object</span> @<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Folder"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.Directory<span class="o">}}</span>,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"FileName"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.Name<span class="o">}}</span> ,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Size"</span>;<span class="nv">Expression</span><span class="o">={</span>Format-FileSize<span class="o">(</span><span class="nv">$_</span>.Length<span class="o">)}}</span>,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Last Modified Date"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.LastWriteTime<span class="o">}}</span>,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Owner"</span>;<span class="nv">Expression</span><span class="o">={(</span><span class="nb">Get-acl</span> <span class="nv">$_</span>.FullName<span class="o">)</span>.Owner<span class="o">}}</span> |
<span class="nb">Format-Table</span> -AutoSize <span class="k">*</span> |
<span class="nb">Out-String</span> -Width 4096
<span class="c1"># Print Results to screen</span>
<span class="nv">$Results</span> | Out-Host
<span class="c1"># Print Count of files found to screen</span>
<span class="nb">Write-Host</span> <span class="s2">"Count: </span><span class="nv">$FilesCount</span><span class="s2">"</span>
<span class="c1"># Add header info to results</span>
<span class="nv">$Message</span> <span class="o">=</span> <span class="nv">$Message</span> + <span class="o">(</span><span class="s2">"="</span> <span class="k">*</span> 11<span class="o">)</span> + <span class="s2">" Searching for </span><span class="nv">$pattern</span><span class="s2"> "</span> + <span class="o">(</span><span class="s2">"="</span> <span class="k">*</span> 11<span class="o">)</span> + <span class="s2">"</span><span class="se">`r`n</span><span class="s2">**Number of Files found: </span><span class="nv">$FilesCount</span><span class="se">`r`n`r`n</span><span class="s2">"</span> + <span class="nv">$Results</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>On the <code class="highlighter-rouge">Select-Object</code> I separated the code to look nicer and show you all the columns I selected in a glance instead of jumbled mess.</p>
<h2 id="write-to-file">Write to file</h2>
<p>Old Code:</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="nv">$file</span> | <span class="nb">Out-File </span>results.txt
<span class="nb">Clear-Variable</span> -name file
<span class="nb">Clear-Variable</span> -Name resultsFile
.\Results.txt
</code></pre></div></div>
<p>New Code:</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="c1"># Send all results information to results.txt File.</span>
<span class="nv">$Message</span> | <span class="nb">Out-File</span> <span class="s2">"</span><span class="nv">$Path</span><span class="s2">\Results.txt"</span>
<span class="c1"># Clear Variables from memory</span>
<span class="nb">Clear-Variable</span> -Name Results
<span class="c1"># Open Results text file in Notepad</span>
<span class="nb">Invoke-Item</span> <span class="s2">"</span><span class="nv">$Path</span><span class="s2">\Results.txt"</span>
</code></pre></div></div>
<p>Here I changed all the paths to explicitly state where everything is going instead of assuming that PowerShell is in the right directory. I also reduced the <code class="highlighter-rouge">Clear-Variable</code> command to one time call since I cleaned up the code earlier. If I don’t clear this variable then if I run the function again it just adds to this variable and I get two sets of results in one. Finally, I explicitly call <code class="highlighter-rouge">Invoke-Item</code> to open the Result.txt file with the Path in the call as well.</p>
<h2 id="validate-script---parameter-validation-attribute">Validate Script - Parameter Validation Attribute</h2>
<p>I got another tip from Reddit User <a href="https://www.reddit.com/user/TheHobbitsGiblets" target="_blank">TheHobbitsGiblets</a> and it was a good one! I have never heard of this feature but I am loving it, it shaved my code down from 16 to 6 lines of code!! Without further ado, here is the code. So before even starting the function I check the <code class="highlighter-rouge">$Path</code> variable and also check to see if both the locations.txt and patterns.txt file exist. If they do then the script will run if not then I throw a default PowerShell error with the appropriate message.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">param</span> <span class="o">(</span>
<span class="o">[</span>Parameter<span class="o">(</span><span class="nv">Mandatory</span><span class="o">=</span><span class="nv">$true</span><span class="o">)]</span>
<span class="o">[</span>ValidateScript<span class="o">({</span>
<span class="k">If</span><span class="o">((</span><span class="nb">Test-Path</span> <span class="nv">$_</span><span class="o">)</span> -and <span class="o">(</span><span class="nb">Test-Path</span> <span class="s2">"</span><span class="nv">$_</span><span class="s2">\locations.txt"</span><span class="o">)</span> -and <span class="o">(</span><span class="nb">Test-Path</span> <span class="s2">"</span><span class="nv">$_</span><span class="s2">\patterns.txt"</span><span class="o">))</span>
<span class="o">{</span> <span class="nv">$true</span> <span class="o">}</span>
<span class="k">else</span>
<span class="o">{</span> <span class="k">Throw</span> <span class="s2">"The path is invalid or Locations.txt/Patterns.txt files are missing."</span> <span class="o">}</span>
<span class="o">})]</span>
<span class="o">[</span><span class="kt">string</span><span class="o">]</span>
<span class="nv">$Path</span>
<span class="o">)</span>
</code></pre></div></div>
<p>When this is ran and the path is not correct and the Locations and Patterns text file.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Retrieve-FilesByPatternLocation : Cannot validate argument on parameter <span class="s1">'Path'</span><span class="nb">.</span> The path is invalid or Locations.txt/Patterns.txt
files are missing.
At line:1 <span class="kt">char</span>:39
</code></pre></div></div>
<h3 id="the-old-code">The old code.</h3>
<p>I was doing it wrong and now I am saving space in my function and being more efficient as you can see I was using aliases and using .Net code and multiple if statements.</p>
<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="o">([</span><span class="kt">string</span><span class="o">]</span>::IsNullOrEmpty<span class="o">(</span><span class="nv">$path</span><span class="o">))</span>
<span class="o">{</span>
<span class="nb">Write-Host</span> <span class="s2">"Exiting script..."</span>
<span class="k">exit</span>
<span class="o">}</span>
<span class="nb">cd</span> <span class="nv">$path</span>
<span class="nv">$locPath</span> <span class="o">=</span> <span class="nv">$path</span> + <span class="s2">"\locations.txt"</span>
<span class="nv">$patternPath</span> <span class="o">=</span> <span class="nv">$path</span> + <span class="s2">"\patterns.txt"</span>
<span class="k">if</span><span class="o">(![</span>System.IO.File]::Exists<span class="o">(</span><span class="nv">$locPath</span><span class="o">)){</span>
<span class="nb">Write-Host</span> <span class="s2">"* Locations text file does not exist in </span><span class="nv">$path</span><span class="s2">. Exiting..."</span> -ForegroundColor Red
<span class="k">Exit</span>
<span class="o">}</span>
<span class="k">if</span><span class="o">(![</span>System.IO.File]::Exists<span class="o">(</span><span class="nv">$patternPath</span><span class="o">)){</span>
<span class="nb">Write-Host</span> <span class="s2">"* Patterns text file does not exist in </span><span class="nv">$path</span><span class="s2">. Exiting..."</span> -ForegroundColor Red
<span class="k">Exit</span>
<span class="o">}</span>
</code></pre></div></div>
<p>I want to thank <a href="https://www.reddit.com/user/Lee_Dailey" target="_blank">Lee_Dailey</a> and <a href="https://www.reddit.com/user/TheHobbitsGiblets" target="_blank">TheHobbitsGiblets</a> for dissecting my code and helping me to see my code thru their eyes plus all the other Reddit users that helped me in my posts for feedback. It was a great experience overall.</p>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/Custom Windows File and Pattern Search in PowerShell script2016-12-26T00:00:00+00:002016-12-26T00:00:00+00:00https://pcast01.github.io/Custom-Windows-Search-Files-Powershell<p>December 26, 2016</p>
<h2 id="custom-windows-search">Custom Windows Search</h2>
<p>I recently worked on a project where I was tasked to create a custom search for a client and he wanted a specific search that would
look at 1 text file filled with windows path locations and 1 text file that has specific words to search for.</p>
<p>Here is the script:
<script src="https://gist.github.com/1593a0f632fa36765a100f085ea81015.js"> </script></p>
<h2 id="breakdown-of-script">Breakdown of script</h2>
<p>The first function I found on an answer this question on <a href="http://superuser.com/questions/468782/show-human-readable-file-sizes-in-the-default-powershell-ls-command">superuser.com</a>
This is used for formatting the size of files found in the script.</p>
<p>Format-FileSize function takes one integer that is the Length property of a file and formats it according to its size. i.e. 1KB, 1MB…</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="k">Function </span>Format-FileSize<span class="o">()</span> <span class="o">{</span>
<span class="k">Param</span> <span class="o">([</span><span class="kt">int</span><span class="o">]</span><span class="nv">$size</span><span class="o">)</span>
<span class="k">If</span> <span class="o">(</span><span class="nv">$size</span> -gt 1TB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} TB"</span>, <span class="nv">$size</span> / 1TB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 1GB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} GB"</span>, <span class="nv">$size</span> / 1GB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 1MB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} MB"</span>, <span class="nv">$size</span> / 1MB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 1KB<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} kB"</span>, <span class="nv">$size</span> / 1KB<span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -gt 0<span class="o">)</span> <span class="o">{[</span><span class="kt">string</span><span class="o">]</span>::Format<span class="o">(</span><span class="s2">"{0:0.00} B"</span>, <span class="nv">$size</span><span class="o">)}</span>
<span class="k">ElseIf</span> <span class="o">(</span><span class="nv">$size</span> -eq 0<span class="o">)</span> <span class="o">{</span><span class="s2">"0 MB"</span><span class="o">}</span>
<span class="k">Else</span> <span class="o">{</span><span class="s2">""</span><span class="o">}</span>
<span class="o">}</span></code></pre></figure>
<h2 id="header-of-the-script-menu">Header of the script menu</h2>
<p>This is the opening screen for the script which shows the Powershell Version from the start and then I do a Read-Host to show this header for the script.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="nv">$ver</span> <span class="o">=</span> <span class="nv">$psversiontable</span>.psversion
<span class="nb">Write-Host</span> <span class="s2">"PowerShell version: </span><span class="nv">$ver</span><span class="s2">"</span>
<span class="nb">Write-Host</span> <span class="s2">"Script Mission: takes a list of locations to search and looks at another "</span>
<span class="nb">Write-Host</span> <span class="s2">" list that has specific words to match and compilates a list"</span>
<span class="nb">Write-Host</span> <span class="s2">" with information about matches found in the filename."</span>
<span class="nb">Write-Host</span> <span class="s2">"---------------------------------------------------------------------"</span>
<span class="nb">Write-Host</span> <span class="s2">" Select Folder where Locations and Patterns text files are located when prompted"</span>
<span class="nv">$startScript</span> <span class="o">=</span> <span class="nb">Read-Host</span> -Prompt <span class="s1">'Hit enter to continue'</span></code></pre></figure>
<h2 id="browse-for-folder-dialog-box">Browse for folder Dialog box</h2>
<p><img src="https://pcast01.github.io/assets/images/BrowseForFolder.png" alt="BrowseForFolder" /></p>
<p>The next part I found some code that will open the BrowseForFolder dialog windows that allows you to navigate to the folder
where the locations and patterns text files are located. Then it checks if both files exists if not then it exits the script.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="nv">$application</span> <span class="o">=</span> <span class="nb">New-Object</span> -ComObject Shell.Application
<span class="nv">$path</span> <span class="o">=</span> <span class="o">(</span><span class="nv">$application</span>.BrowseForFolder<span class="o">(</span>0, <span class="s1">'Select root folder of new WebSite'</span>, 0<span class="o">))</span>.Self.Path
<span class="k">if</span><span class="o">([</span><span class="kt">string</span><span class="o">]</span>::IsNullOrEmpty<span class="o">(</span><span class="nv">$path</span><span class="o">))</span>
<span class="o">{</span>
<span class="nb">Write-Host</span> <span class="s2">"Exiting script..."</span>
<span class="k">exit</span>
<span class="o">}</span>
<span class="nb">cd</span> <span class="nv">$path</span>
<span class="nv">$locPath</span> <span class="o">=</span> <span class="nv">$path</span> + <span class="s2">"\locations.txt"</span>
<span class="nv">$patternPath</span> <span class="o">=</span> <span class="nv">$path</span> + <span class="s2">"\patterns.txt"</span>
<span class="k">if</span><span class="o">(![</span>System.IO.File]::Exists<span class="o">(</span><span class="nv">$locPath</span><span class="o">)){</span>
<span class="nb">Write-Host</span> <span class="s2">"* Locations text file does not exist in </span><span class="nv">$path</span><span class="s2">. Exiting..."</span> -ForegroundColor Red
<span class="k">Exit</span>
<span class="o">}</span></code></pre></figure>
<h2 id="get-childitem-with-select-object">Get-ChildItem with Select-Object</h2>
<p>The function is used when creating a new object for <a href="http://ss64.com/ps/select-object.html">Select-Object</a> and the name of it is Size. The expression is going to be the function Format-FileSize and
we will pass it the Length property which is the number of bytes for the file.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> @<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Size"</span>;<span class="nv">Expression</span><span class="o">={</span>Format-FileSize<span class="o">(</span><span class="nv">$_</span>.Length<span class="o">)}}</span></code></pre></figure>
<h2 id="the-major-part-of-the-script">The major part of the script</h2>
<p>I perform 2 <a href="http://ss64.com/ps/foreach.html">foreach</a> loops starting with the locations text file and start with the first location then I start the next <a href="http://ss64.com/ps/foreach.html">foreach</a>
thru all the patterns to search for in the first location and all its subfolders using this line:</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="nv">$files</span> <span class="o">=</span> <span class="nb">gci</span> -Path <span class="nv">$folder</span> -Recurse <span class="k">*</span>.<span class="k">*</span><span class="s2">"</span></code></pre></figure>
<p>To search all recursively down the folders we must get all the files using <a href="http://ss64.com/ps/get-childitem.html">Get-ChildItem</a> and using <a href="http://ss64.com/ps/where-object.html">Where-Object</a>.
I filter all the files out by using $_.PSIsContainer -eq $false. * If we wanted folders then this would be equal to True instead of false</p>
<p>The other condition is where Name property is -like “<em>$pattern</em>”. * I use the star(*) character as a wildcard on both sides so we can find the pattern anywhere in the title.</p>
<p>I then pipe the results to <a href="http://ss64.com/ps/select-object.html">Select-Object</a> to get all custom properties:</p>
<ul>
<li>Folder - Directory of file</li>
<li>Size - Use Format-FileSize function and pass Length of file in bytes.</li>
<li>Last Modified Date - LastWriteTime of file.</li>
<li>Owner - Use Get-Acl cmdlet and pass it the fullName of the file</li>
</ul>
<p>I then pipe those results to <a href="http://ss64.com/ps/format-table.html">Format-Table -AutoSize</a> and pipe that to <a href="https://poshoholic.com/2010/11/11/powershell-quick-tip-creating-wide-tables-with-powershell/">Out-String -Width 4096</a> and it will be printed later to the text file.</p>
<p>I print the results of this in the line “$resultsFile” then I get the count of files from “$rCount = $rNumbers.Count” and then “Write-Host ‘Count: $rCount’”</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="k">foreach</span> <span class="o">(</span><span class="nv">$folder</span> <span class="k">in</span> <span class="nv">$folders</span><span class="o">)</span> <span class="o">{</span>
<span class="nv">$files</span> <span class="o">=</span> <span class="nb">gci</span> -Path <span class="nv">$folder</span> -Recurse <span class="k">*</span>.<span class="k">*</span>
<span class="nb">Write-Host</span> <span class="s2">"Searching folder: </span><span class="nv">$folder</span><span class="s2"> -------------------------"</span>
<span class="nv">$file</span> <span class="o">=</span> <span class="nv">$file</span> + <span class="s2">"********************************************************************</span><span class="se">`r`n</span><span class="s2">Searching folder: </span><span class="nv">$folder</span><span class="se">`r`n</span><span class="s2">********************************************************************</span><span class="se">`r`n</span><span class="s2">"</span>
<span class="k">foreach</span> <span class="o">(</span><span class="nv">$pattern</span> <span class="k">in</span> <span class="nv">$patterns</span><span class="o">)</span> <span class="o">{</span>
<span class="nv">$resultsFile</span> <span class="o">=</span> <span class="nb">Get-ChildItem</span> -Recurse -Force <span class="nv">$folder</span> -ErrorAction SilentlyContinue |
<span class="nb">Where</span>-Object <span class="o">{</span> <span class="o">(</span><span class="nv">$_</span>.PSIsContainer -eq <span class="nv">$false</span><span class="o">)</span> -and <span class="o">(</span> <span class="nv">$_</span>.Name -like <span class="s2">"*</span><span class="nv">$pattern</span><span class="s2">*"</span><span class="o">)</span> <span class="o">}</span> |
<span class="nb">Select-Object</span> @<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Folder"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.Directory<span class="o">}}</span>,@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"FileName"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.Name<span class="o">}}</span> ,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Size"</span>;<span class="nv">Expression</span><span class="o">={</span>Format-FileSize<span class="o">(</span><span class="nv">$_</span>.Length<span class="o">)}}</span>, @<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Last Modified Date"</span>;<span class="nv">Expression</span><span class="o">={</span><span class="nv">$_</span>.LastWriteTime<span class="o">}}</span>,
@<span class="o">{</span><span class="nv">Name</span><span class="o">=</span><span class="s2">"Owner"</span>;<span class="nv">Expression</span><span class="o">={(</span><span class="nb">Get-acl</span> <span class="nv">$_</span>.FullName<span class="o">)</span>.Owner<span class="o">}}</span> | <span class="nb">Format-Table</span> -AutoSize <span class="k">*</span> | <span class="nb">Out-String</span> -Width 4096
<span class="nv">$rNumbers</span> <span class="o">=</span> <span class="nb">Get-ChildItem</span> -Recurse -Force <span class="nv">$folder</span> -ErrorAction SilentlyContinue | <span class="nb">Where</span>-Object <span class="o">{</span> <span class="o">(</span><span class="nv">$_</span>.PSIsContainer -eq <span class="nv">$false</span><span class="o">)</span> -and <span class="o">(</span> <span class="nv">$_</span>.Name -like <span class="s2">"*</span><span class="nv">$pattern</span><span class="s2">*"</span><span class="o">)</span> <span class="o">}</span>
<span class="nv">$resultsFile</span>
<span class="nv">$rCount</span> <span class="o">=</span> <span class="nv">$rNumbers</span>.Count
<span class="nb">Write-Host</span> <span class="s2">"Count: </span><span class="nv">$rCount</span><span class="s2">"</span>
<span class="nv">$file</span> <span class="o">=</span> <span class="nv">$file</span> + <span class="s2">"=========== Searching for </span><span class="nv">$pattern</span><span class="s2"> ===========</span><span class="se">`r`n</span><span class="s2">**Number of Files found: </span><span class="nv">$rCount</span><span class="se">`r`n`r`n</span><span class="s2">"</span> + <span class="nv">$resultsFile</span>
<span class="o">}</span>
<span class="o">}</span></code></pre></figure>
<h2 id="write-to-file">Write to file</h2>
<p>Next I write all the results for the first Pattern to the $file variable. After searching all locations I finally pipe all the results to a file in the current directory called results.txt.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="nv">$file</span> | <span class="nb">Out-File </span>results.txt
<span class="nb">Clear-Variable</span> -name file
<span class="nb">Clear-Variable</span> -Name resultsFile
.\Results.txt</code></pre></figure>
<p>At the end of the script I clear the two variables: file and resultsFile. Then I open the Results.txt file for review.</p>
<p>Here are results for 2 locations with 2 search patterns: <em>excerpte</em>.jpg and *.aspx</p>
<ul>
<li>so all aspx files and jpg files with excerpte in the title.</li>
</ul>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="k">********************************************************************</span>
Searching folder: C:\Temp
<span class="k">********************************************************************</span>
<span class="o">===========</span> Searching <span class="k">for</span> <span class="k">*</span>excerpte<span class="k">*</span>.jpg <span class="o">===========</span>
<span class="k">**</span>Number of Files found: 1
Folder FileName Size Last Modified Date Owner
------ -------- ---- ------------------ -----
C:\Temp DoD Pest Management DPHSexcerpte.jpg 5.86 MB 8/26/2016 4:40:11 PM Owner
<span class="o">===========</span> Searching <span class="k">for</span> <span class="k">*</span>.aspx <span class="o">===========</span>
<span class="k">**</span>Number of Files found: 2
Folder FileName Size Last Modified Date Owner
------ -------- ---- ------------------ -----
C:\Temp\Test Logoff.aspx 4.62 kB 11/1/2016 12:06:41 PM Owner
C:\Temp\Test Template App\admin Logoff.aspx 4.62 kB 11/1/2016 12:06:41 PM Owner
<span class="k">********************************************************************</span>
Searching folder: C:\Test
<span class="k">********************************************************************</span>
<span class="o">===========</span> Searching <span class="k">for</span> <span class="k">*</span>excerpte<span class="k">*</span>.jpg <span class="o">===========</span>
<span class="k">**</span>Number of Files found: 4
Folder FileName Size Last Modified Date Owner
------ -------- ---- ------------------ -----
C:\Test excerpte1.jpg 0 MB 12/16/2016 11:40:06 AM Owner
C:\Test excerpteTENS.jpg 0 MB 12/16/2016 11:47:11 AM Owner
C:\Test\level1\Level2\Level3 excerpte12.jpg 0 MB 12/16/2016 11:40:06 AM Owner
C:\Test\level1\Level2\Level3 excerpteThirteen.jpg 0 MB 12/16/2016 11:47:11 AM Owner
<span class="o">===========</span> Searching <span class="k">for</span> <span class="k">*</span>.aspx <span class="o">===========</span>
<span class="k">**</span>Number of Files found: 0</code></pre></figure>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/Beginner’s guide to PowerShell part 2 - Functions2016-11-18T00:00:00+00:002016-11-18T00:00:00+00:00https://pcast01.github.io/get-started-with-Powershell-part2<p>November 18, 2016</p>
<h2 id="functions">Functions</h2>
<p>If you find that you are running a certain script all the time then the best thing to do is to create it as a function. But there are also other benefits to using functions.
When you create a function, the name you have for the function is now a command inside your PowerShell session.</p>
<p>Now I prefer using <a href="https://msdn.microsoft.com/en-us/powershell/scripting/getting-started/fundamental/windows-powershell-integrated-scripting-environment--ise-">PowerShell ISE</a> when creating script because of its ease of use.</p>
<p>When you open PowerShell ISE the top part is the script pane and this is where you can input multiple lines of PowerShell and save them as *.ps1 files.
You can create just regular code here or you can create functions.</p>
<p>Here is an example of a function that opens up a text file using notepad and the location of the text file is located in C:\Test folder.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="k">function </span>Notes <span class="o">{</span>
notepad <span class="s2">"C:\Test\notes.txt"</span>
<span class="o">}</span></code></pre></figure>
<p>When you click the play button on the top your function executes inside the code window. Once its ran then it’s loaded in PowerShell for use again with just using the name of the function which is Notes.
<a href="https://pcast01.github.io/assets/images/PowershellIDE_NotesFunction-min.png" target="_blank">
<img src="https://pcast01.github.io/assets/images/PowershellIDE_NotesFunction-min.png" alt="PowerShell ISE" /></a>
<a href="https://pcast01.github.io/assets/images/PowershellIDE_NotesFunction-min.png">Enlarge image</a></p>
<p>Now type Notes into the command window and then Notepad opens up with your document.
<a href="https://pcast01.github.io/assets/images/PowerShellIDE_NotesFunction3-min.png" target="_blank">
<img src="https://pcast01.github.io/assets/images/PowershellIDE_NotesFunction3-min.png" alt="PowerShell ISE" /></a>
<a href="https://pcast01.github.io/assets/images/PowershellIDE_NotesFunction3-min.png">Enlarge image</a></p>
<h2 id="functions-with-parameters">Functions with parameters</h2>
<p>The next thing to learn is <a href="http://ss64.com/ps/syntax-functions.html">functions</a> with parameters and here is an example of one below.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="k">function </span>Sum <span class="o">{</span>
<span class="k">param</span><span class="o">(</span>
<span class="o">[</span><span class="kt">int</span><span class="o">]</span><span class="nv">$firstNumber</span>,
<span class="o">[</span><span class="kt">int</span><span class="o">]</span><span class="nv">$secondNumber</span>
<span class="o">)</span>
<span class="nv">$firstNumber</span> + <span class="nv">$secondNumber</span>
<span class="o">}</span>
Sum -firstNumber 1 -secondNumber 2
3
Sum 1 2
3</code></pre></figure>
<p>The syntax of a function is important to learn to do correctly. When declaring parameters it is crucial that you put the $ dollar sign in front of every parameter. Also you can optionally declare the type of variable and in this case I have declared both the parameters as integers.</p>
<p>Here is the exact same function but without declaring the type for the parameters and it achieves the same result.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="k">function </span>SumWO <span class="o">{</span>
<span class="k">param</span><span class="o">(</span>
<span class="nv">$first</span>,
<span class="nv">$second</span>
<span class="o">)</span>
<span class="nv">$first</span> + <span class="nv">$second</span>
<span class="o">}</span>
SumWO -firstNumber 1 -secondNumber 2
3
SumWO 1 2
3</code></pre></figure>
<p>The other part is you can use <a href="http://ss64.com/ps/syntax-tab-completion.html" target="_blank">Tab Completion</a> in PowerShell.</p>
<p>When I type sum(lowercase) I hit Tab right after and it finds my function and changes it to Sum. After that I hit spacebar then a dash. I hit Tab again and PowerShell shows me the first parameter. Then I hit spacebar again and type in the number 1. I type another dash then Tab and it gives me the second parameter, I hit spacebar again and then type 2. After all that I hit Enter and the function executes with the parameters and returns a 3 on the next line. I then type cls to clear the screen. The command <a href="http://ss64.com/nt/cls.html" target="_blank">cls</a> is an alias for <a href="http://ss64.com/ps/clear-host.html">Clear-Host</a> command in PowerShell.</p>
<p><img src="https://pcast01.github.io/assets/images/SumCLS.gif" alt="PowerShell ISE" /></p>
<h2 id="functions-with-default-parameters">Functions with default parameters</h2>
<p>Functions also have a way to set parameters with default values. So say you want to create the same function we have been using but want to set both the firstNumber and secondNumber with a default value. So if you just run Sum in powershell it won’t require you to put in a variable.</p>
<p>Currently if you run the function with no parameters then the value automatically comes back as 0.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="k">function </span>Sum <span class="o">{</span>
<span class="k">param</span><span class="o">(</span>
<span class="nv">$first</span>,
<span class="nv">$second</span>
<span class="o">)</span>
<span class="nv">$first</span> + <span class="nv">$second</span>
<span class="o">}</span>
Sum
0</code></pre></figure>
<p>But if we specify default values for each parameter, in this case 2 for each value. When you run the sum command now it will be equal to 4.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="k">function </span>Sum <span class="o">{</span>
<span class="k">param</span><span class="o">(</span>
<span class="nv">$first</span><span class="o">=</span>2,
<span class="nv">$second</span><span class="o">=</span>2
<span class="o">)</span>
<span class="nv">$first</span> + <span class="nv">$second</span>
<span class="o">}</span>
Sum
4</code></pre></figure>
<h2 id="functions-with-required-parameters">Functions with Required parameters</h2>
<p>Also to help you starting with Windows PowerShell 2.0 and above, there is a <a href="http://ss64.com/ps/syntax-args.html">parameter attribute</a> you can use to require a parameter.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="o">[</span>Parameter<span class="o">(</span><span class="nv">Mandatory</span><span class="o">=</span><span class="nv">$true</span><span class="o">)]</span></code></pre></figure>
<p>When you use this above your declared parameter then the function requires you to input a parameter.</p>
<p>In this example we have set both parameters to be mandatory.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="k">function </span>Sum <span class="o">{</span>
<span class="k">param</span><span class="o">(</span>
<span class="o">[</span>Parameter<span class="o">(</span><span class="nv">Mandatory</span><span class="o">=</span><span class="nv">$true</span><span class="o">)]</span>
<span class="o">[</span><span class="kt">int</span><span class="o">]</span><span class="nv">$firstNumber</span>,
<span class="o">[</span>Parameter<span class="o">(</span><span class="nv">Mandatory</span><span class="o">=</span><span class="nv">$true</span><span class="o">)]</span>
<span class="o">[</span><span class="kt">int</span><span class="o">]</span><span class="nv">$secondNumber</span>
<span class="o">)</span>
<span class="nv">$firstNumber</span> + <span class="nv">$secondNumber</span>
<span class="o">}</span></code></pre></figure>
<p>When we use the function now PowerShell will not let us use the function without inputting a value for each parameter.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="nb">PS</span>:> Sum
cmdlet Sum at <span class="nb">command </span>pipeline position 1
Supply values <span class="k">for </span>the following parameters:
firstNumber: </code></pre></figure>
<p>Then for the second number.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="nb">PS</span>:> Sum
cmdlet Sum at <span class="nb">command </span>pipeline position 1
Supply values <span class="k">for </span>the following parameters:
firstNumber: 1
secondNumber: 1</code></pre></figure>
<p>And finally.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"><span class="nb">PS</span>:> Sum
cmdlet Sum at <span class="nb">command </span>pipeline position 1
Supply values <span class="k">for </span>the following parameters:
firstNumber: 1
secondNumber: 2
3
<span class="nb">PS</span>:> </code></pre></figure>
<p>This is just a high level view of functions and we will get into PowerShell profile next.</p>
<h2 id="powershell-links">PowerShell links</h2>
<p><a href="http://ss64.com/ps/">PowerShell references</a></p>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/Beginner’s guide to PowerShell2016-11-06T00:00:00+00:002016-11-06T00:00:00+00:00https://pcast01.github.io/get-started-with-Powershell<p>November 06, 2016</p>
<blockquote>
<p>If you repeat it, PowerShell it.</p>
</blockquote>
<p>I like making my everyday job easier so scripting repeat things I do every day is key for me. I found that if I am typing something more than once a day I might as well create a script to automate this process.
Some ways that I use PowerShell everyday is for instance:
<strong>Clearing internet cache, Lookups in SQL databases, Run Stored Procedures, Connect RDP automatically, bring text into my clipboard, Search multiple text files, and the list goes on and on.</strong></p>
<p>If are familiar with the .Net Framework you can also tap into any commands available on Windows. So basically all windows machines by default have PowerShell built into it.</p>
<p>Currently there are 6 versions of PowerShell and to check what version you have on your machine just go into PowerShell and run the command $PSVersionTable and the Version is your version number of PowerShell.</p>
<p><em>*PowerShell is also available in Linux.</em></p>
<h2 id="how-to-find-powershell-on-your-computer">How to find PowerShell on your computer</h2>
<p>Using Windows 10, 8, 7:
Click Start button and start typing PowerShell and you will see many different types. The best one to start with in my opinion is PowerShell ISE.</p>
<p>The PowerShell ISE is Microsoft’s PowerShell default script IDE.
<img src="https://pcast01.github.io/assets/images/powershellIDE.png" alt="powershell ISE" />
The top part is for script files that you can test out your script and then get the results on the bottom. You can customize the layout any way you like.
Next, if you are going to be creating scripts then you should set the security of PowerShell to allow you to run scripts.</p>
<h2 id="first-things-first">First things first</h2>
<p>If you plan on creating any script files the first command you should execute inside PowerShell is this one.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="nb">Set-ExecutionPolicy</span> -ExecutionPolicy Bypass -Scope CurrentUser</code></pre></figure>
<p>PowerShell also allows you to use the up arrow to get the last command executed.</p>
<p>By default, PowerShell doesn’t allow outright execution of ps1 files(scripts). So you must tell PowerShell that the security must allow the current user to execute scripts.
This is not mandatory when first learning PowerShell and it is setup so that you cannot mess up anything in the Operating system by default.</p>
<h2 id="powershell-profiles">Powershell Profiles</h2>
<p>Each PowerShell window that you open has an associated profile that is a file located in various places inside Windows.
If you type:</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="nv">$profile</span></code></pre></figure>
<p>You will see the path and name of your profile location.
If you want you can put in this command to open your profile inside of Notepad.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> notepad <span class="nv">$profile</span></code></pre></figure>
<p>Once in your profile file you can add PowerShell code to run every time you first start it. For instance, you can use the code below to get all the paths located in your System Environment variables and save them as PSDrives.</p>
<h3 id="profile-example-code">Profile example code</h3>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="nv">$names</span> <span class="o">=</span> <span class="o">[</span>Environment+SpecialFolder]::GetNames<span class="o">([</span>Environment+SpecialFolder]<span class="o">)</span>
<span class="k">foreach</span><span class="o">(</span><span class="nv">$name</span> <span class="k">in</span> <span class="nv">$names</span><span class="o">)</span>
<span class="o">{</span>
<span class="k">if</span><span class="o">(</span><span class="nv">$path</span> <span class="o">=</span> <span class="o">[</span>Environment]::GetFolderPath<span class="o">(</span><span class="nv">$name</span><span class="o">)){</span>
<span class="nb">New-PSDrive</span> -Name <span class="nv">$name</span> -PSProvider FileSystem -Root <span class="nv">$path</span> | Out-Null
<span class="o">}</span>
<span class="o">}</span></code></pre></figure>
<p>This allows me to select a drive or location and navigate there quickly. Such as this one called desktop and it takes me directly to my desktop.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="nb">cd </span>desktop:</code></pre></figure>
<h2 id="basic-syntax">Basic Syntax</h2>
<p>Wikipedia has the best interpretation/definition of PowerShell.</p>
<blockquote>
<p>PowerShell (including Windows PowerShell and PowerShell Core) is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework.
— Wikipedia</p>
</blockquote>
<h3 id="variables">Variables</h3>
<p>All variables start with a $ Dollar sign. This signifies a variable and there are several different types:</p>
<table>
<thead>
<tr>
<th style="text-align: center">Data Type Name</th>
<th style="text-align: center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center">[Array]</td>
<td style="text-align: center">Array</td>
</tr>
<tr>
<td style="text-align: center">[Bool]</td>
<td style="text-align: center">Value is TRUE or FALSE</td>
</tr>
<tr>
<td style="text-align: center">[DateTime]</td>
<td style="text-align: center">Date and time</td>
</tr>
<tr>
<td style="text-align: center">[Guid]</td>
<td style="text-align: center">Globally unique 32-byte identifier</td>
</tr>
<tr>
<td style="text-align: center">[HashTable]</td>
<td style="text-align: center">Hash table, collection of key-value pairs</td>
</tr>
<tr>
<td style="text-align: center">[Int32], [Int]</td>
<td style="text-align: center">32-bit integers</td>
</tr>
<tr>
<td style="text-align: center">[PsObject]</td>
<td style="text-align: center">PowerShell object</td>
</tr>
<tr>
<td style="text-align: center">[Regex]</td>
<td style="text-align: center">Regular expression</td>
</tr>
<tr>
<td style="text-align: center">[ScriptBlock]</td>
<td style="text-align: center">PowerShell script block</td>
</tr>
<tr>
<td style="text-align: center">[Single], [Float]</td>
<td style="text-align: center">Floating point number</td>
</tr>
<tr>
<td style="text-align: center">[String]</td>
<td style="text-align: center">String</td>
</tr>
<tr>
<td style="text-align: center">[Switch]</td>
<td style="text-align: center">PowerShell switch parameter</td>
</tr>
<tr>
<td style="text-align: center">[TimeSpan]</td>
<td style="text-align: center">Time interval</td>
</tr>
<tr>
<td style="text-align: center">[XmlDocument]</td>
<td style="text-align: center">XML document</td>
</tr>
</tbody>
</table>
<p>You can create a variable with a $ dollar sign or you can put the data type first then the $ dollar sign.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="nv">$test</span> <span class="o">=</span> <span class="s2">"testing"</span>
<span class="o">[</span><span class="kt">string</span><span class="o">]</span><span class="nv">$teststring</span> <span class="o">=</span> <span class="s2">"testing"</span></code></pre></figure>
<p>Both variables are of type string.</p>
<p>You can also use it like a calculator</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="nv">$count</span> <span class="o">=</span> 1
<span class="nv">$count</span> +<span class="o">=</span> 1
<span class="nv">$count</span>
2</code></pre></figure>
<p>You also have access to .Net methods inside PowerShell.</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="o">[</span>Math]::pow<span class="o">(</span>2,2<span class="o">)</span>
4</code></pre></figure>
<p>This is the Math class using the method pow which takes two integers and the first one is value and the second is the power.</p>
<h2 id="powershell-basic-cmdlets-to-get-started-with">PowerShell basic cmdlets to get started with</h2>
<p>The three basic cmdlets to get started with right away are:</p>
<ol>
<li><a href="http://ss64.com/ps/get-command.html">Get-Command</a></li>
<li><a href="http://ss64.com/ps/get-help.html">Get-Help</a></li>
<li><a href="http://ss64.com/ps/get-member.html">Get-Member</a></li>
</ol>
<p>The basic syntax of all PowerShell commands follow a pattern. That pattern is Verb-Noun. So you can see by applying this to these three commands its Get and then whatever it is you are using.</p>
<ol>
<li><strong>Get-Command</strong> - This will get all the commands available to you in your current session.
<img src="https://pcast01.github.io/assets/images/get_command-min.png" alt="Get-Command" />
This is useful because now you know what commands are available to you.</li>
</ol>
<p>To search on a specific verb you can use this command:</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> Get-Command -verb get</code></pre></figure>
<p><img src="https://pcast01.github.io/assets/images/get_commandVerb-min.png" alt="Get-Command by Verb" /></p>
<ol>
<li><strong>Get-Help</strong> - This is especially helpful to get the exact properties of a command or variable that PowerShell has available.
To get all help then type:</li>
</ol>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> Get-Help <span class="k">*</span></code></pre></figure>
<p>Or you can lookup a specific command like this gci which is an alias for <a href="http://ss64.com/ps/get-childitem.html">Get-ChildItem</a> which is PowerShell’s version of dir in Shell or ls in Linux)</p>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> Get-Help <span class="nb">gci</span></code></pre></figure>
<p><img src="https://pcast01.github.io/assets/images/get_helpGCI-min.png" alt="Get-Help GCI" />
As you can see the <a href="http://ss64.com/ps/get-help.html">Get-Help</a> gives you the description and syntax. I find this extremely helpful when I need a quick example of how to correctly execute a command. You can also use parameter -Full to display the entire help file of a command.</p>
<ol>
<li><strong>Get-Member</strong> - This command gives us information about the object’s properties and Methods.
For an example of how this works lets go back to our earlier example:</li>
</ol>
<figure class="highlight"><pre><code class="language-powershell" data-lang="powershell"> <span class="nv">$count</span> <span class="o">=</span> 1
<span class="nb">Get-Member</span> -InputObject <span class="nv">$count</span></code></pre></figure>
<p>The output shows us that the variable we created is an Int32 variable.
<img src="https://pcast01.github.io/assets/images/get_member_count_close-min.png" alt="Get-Member close $count" /></p>
<p>This is just a quick preview of what PowerShell is capable of next I want to delve into creating functions which is a great way to put tasks into one easy command to execute your scripts.</p>Paul Castilloazrael7@gmail.comhttps://paulbcastillo.me/