Jaa


Calling a PowerShell Function

I’m back from lots of traveling (why I’ve had time to post a few things).

I got a great question about my last post…how best to call a custom PowerShell function. 

I’m not a PowerShell expert by any stretch of the imagination, but I do use it a good amount and I find it useful to save code that I’ve optimized (gotten to actually run!) so can use it over again – like the VMCPU code from my last post.  Copy & Paste a Function

Sometimes I’ll simply copy and past a function directly into PowerShell – that way I don’t have to worry about loading  the script file (execution policy).  Here’s what it looked like when I copied the Report-VMCPU function into PowerShell and called it.

It’s not a convenient way to manage your functions, but you don’t encounter all the security “challenges”.  you might otherwise encounter.

You can of course simply load a “.PS1” which contains your pre-defined functions (like say, a file called Report-VMCPU.PS1 that contains , but the default execution policy may block your ability to load a script file.  To allow the execution of scripts, you may need to run:

set-executionpolicy –executionpolicy unrestricted

Load and Run With Warnings

To then load the script file, type a period followed by a space and the full path to the script file (if it’s in the current directory, then you would enter:

   . .\Report-VMCPU.ps1

Unblock File

You may receive another warning about “Running scripts you trust”.  Some files may be “blocked” based on their security status.  To “unblock” your script file,  hop into Explorer and access file properties.  Click the “Unblock” button and “Apply” for your script.

If you’ve set your execution policy and unblock your script, loading your file full of functions is much cleaner.

Clean load and function call

 

 

 

 

Depending on where I’m working, or what I’m doing, calling a PowerShell function (from my bag of tricks) could look like any of the examples screens above.

As always, keep the comments and questions coming!

-John