Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Calling functions from a imported module and Regex

$
0
0

Hi

I am sure this is going to be a very easy question for most Powershell scripters.... My goal is to validate the value of a variable in an array to ensure it only has the accepted characters, a-z and -. This is to ensure users given and surnames don't have numbers or illegal characters. 

I have a module file, with contains a list of command functions I use in multiple scripts...saves copying the function between script files. I use the "import-module File.psm1" to import the file.

2 of the functions in this module(below), handle testing of expressions.. I pass a value in the pipe and parameters to "Function Test-TryReverseRegex" which then calls function Test-TryExpression, this then tests the expression and throws an exception on False and passes back True if successful.

I am calling the functions with below line. This line is in a Try - Catch so if it fails...it catches the exception

$CSVRecord.str_Given_Name           | Test-NTryReverseRegex -Match "[^-+a-z]" -FailMessage "$field not valid" | Out-Null

My problem is, it passes back a false when it should be true... arghh its driving me nuts. If I copy the functions into the main powershell script file (modify the function names slightly) and call them....it works correctly...so what is the suble difference I am missing?

Any help, whole heartedly appreciated. :)

Nyobi

Function Test-TryReverseRegex {
    param(
        [Parameter(Mandatory=$True, ValueFromPipeline=$true)]
        $Value,
        [Parameter(Mandatory=$True)]
        [string]$Match,
        [switch]$Passthru,
        [string]$FailMessage
    )
    PROCESS {
        write-host "yeah"
        $value | Test-TryExpression -Expression {$_ -notmatch $Match} -FailMessage $FailMessage -Passthru:$Passthru -NoClosure
    }
}

#*******************************

Function Test-TryExpression {
    param(
        [Parameter(Mandatory=$True, ValueFromPipeline=$true, Position=1)]
        $Value,
        [Parameter(Mandatory=$True, Position=0)]
        [scriptblock]$Expression,
        [switch]$Passthru,
        [string]$FailMessage = "Failed to evaluate expression to TRUE.",
        [switch]$NoClosure
    )
   
    PROCESS {
        $global:my = $myinvocation
        $global:cs = Get-PSCallStack
        $_ = $Value
        if($NoClosure){
            [bool]$result = .$expression
        } else {
            [bool]$result = .$expression.GetNewClosure()
        }
        if(!$result) {
            throw $FailMessage
        } else {
            if($Passthru) {
                $value
            } else {
                $true
            }
        }
    }
}


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>