So here is what I did step by step to solve this problem.
Step 1: Set-ExecutionPolicy
So being the person I am I just jumped right in and started doing crazy totally wrong stuff. And of course I ended up working backwards. So the first thing you need to do is set the "ExecutionPolicy" in PowerShell.
There are 4 policy levels:
1) Restricted (default, This doesn't all you to run any script file at all)
2) RemoteSigned (Allows you to run scripts you wrote yourself)
3) AllSigned (Allows you to run all scripts as long as they are signed)
4) Unrestricted (Allows every script to run)
After some consideration (not much) I choose to just use the "Unrestricted" policy. This just allows me to write the script and run it.
So to set this policy you must run PowerShell as administrator. This is required because it changes the register which isn't available unless your running as administrator. Once this is done go ahead and enter this command:
Set-ExecutionPolicy Unrestricted
To make sure this runs successfully you can use the command:
Get-ExecutionPolicy
After you run this command you should see "Unrestricted" on the screen or what ever policy you have chosen.
What PowerShell should look like after you run the "Get-ExecutionPolicy" command |
Step 2: Write Your PowerShell Script
Now you can write whatever PowerShell script you want. I will go ahead and just used the script I am running. What I did was simply opened up a text document and dropped in the following text:
cd "C:\Projects\What\Ever\Your\Path\Is" (dir -include *.xaml -recurse | select-string .).Count
The save this file as a ".ps1" file. This file extension is very important or else you won't be able to run the file in PowerShell. I named my file "count-xaml.ps1" and saved it to my desktop.
Step 3: Write Your Batch File
Again just open up Notepad and type the following command. Of course replace the file name on the first line with what you named you file.
powershell.exe -file count-xaml.ps1 PAUSE
Then I also just saved this to my desktop.
Step 4: Run Your Batch File
Just run your batch file and it should open right up and run. Whatever directory you choose in your .ps1 file will be looped through and all the lines in the XAML files will be counted. The more files you have the longer it will take. Pretty nifty if I say so myself.
After you run your batch file |
Wrap Up
Writing PowerShell scripts is pretty simple once you figure out all the nuts and bolts. Hopefully this helps you to write some PowerShell scripts. Go ahead and rub it in your colleague's face. You know you want to.
No comments:
Post a Comment