Home > Mobile >  Don't Understand what this code is supposed to do?
Don't Understand what this code is supposed to do?

Time:08-10

I copied this code from the internet and was reviewing it for possible upgrading. However, I can't for the life of me figure what the last 2 lines of this snip are supposed to accomplish. In fact I can delete them from a running program I use the code in and the program continues to function normally. I would normally just assume it was leftover junk that didn't get deleted but I found the same last 4 lines of code in another program.

#------------------- Add ClipBoard Watcher Code --------------
# This script is a small update to the one found here:
# https://mnaoumov.wordpress.com/2013/08/31/cpowershell-clipboard-watcher/

# This started in this SO thread: https://stackoverflow.com/q/71014273/147637
# This is expected to run fine on Win10 and Win11 (and probably other versions)

# This script binds the OS functions to monitor when new items are put on the clipboard.
# It is a powershell script, that has been tested to work. 

$script:ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest
function PSScriptRoot { $MyInvocation.ScriptName | Split-Path }
Trap { throw $_ }

Note: I searched the program for references to PsScriptRoot and they don't exist except for the name of this function which is never called.

CodePudding user response:

$script:ErrorActionPreference = "Stop"
Trap { throw $_ }

The trap statement is redundant, because setting the $ErrorActionPreference preference variable to Stop by itself has the effect of promoting both non-terminating and statement-terminating errors to script-terminating (fatal) errors.

Set-StrictMode -Version Latest

In production code, it is ill-advised to use -Version Latest with Set-StrictMode, because the code may break in future PowerShell versions should they include additional strictness checks that your code then could fail.

function PSScriptRoot { $MyInvocation.ScriptName | Split-Path }

Without this function definition ever getting called, it amounts to dead weight, as Abraham Zinala points out.

As an aside: While the function's name suggests that it's trying to duplicate the value of the automatic $PSScriptRoot variable (for which there is no good reasons, since the variable has been available since v2), it returns something different: $MyInvocation.ScriptName contains the path of the calling script, if any, not that of the running script.

  • Related