Help creating a function

This topic contains 5 replies, has 4 voices, and was last updated by  Ed O’Connor 1 year, 12 months ago.

  • Author
    Posts
  • #32972

    Ed O’Connor
    Participant

    Hi,

    I am trying to create a function that will test/validate a command and am having issues getting it working correctly. What I am looking to do is test to see if I can query/run a command to see if the Windows Firewall is Enabled or Disabled.

    Here is what I have:

    function Test-TargetResourse
    {
        param
        (
            [parameter(Mandatory = $true)]
            [ValidateNotNullOrEmpty()]
            [System.String]
            $Enabled,
    
            [System.String]
            [ValidateSet("True", "False")]
            $Ensure = "True"
        )
    
        $firewalls = (Get-NetFirewallProfile | select -expand $enabled)
    
    
        if($Ensure -eq 'False')
        {
            return ($firewalls.Enabled -eq "False")
        }
        else
        {
            return ($firewalls.Enabled -eq "True")
        }
    }
    

    If I run this in ISE nothing happens, no Red no nothing. Any guidance is greatly appreciated.

    Thanks again

  • #32976

    Bob McCoy
    Participant

    Are you loading the function before trying to use it?

    . C:\path-to-function\Test-TargetResource.ps1
    

    Next, you should -ExpandProperty Enabled, not $enabled.

    Finally, you're expecting a mandatory parameter of $Enabled that you are setting to $true, but then casting as a string. Why are you doing that?

  • #32982

    Dan Potter
    Participant

    that's all unnecessary.

    function Test-TargetResourse
    {

    param($computername)

    $firewall = (Get-NetFirewallProfile -name domain -CimSession $computername | select enabled)

    $firewall

    }

  • #32984

    Dan Potter
    Participant

    [bool]((Get-NetFirewallProfile -name domain).enabled -eq 'True')

  • #32986

    Ed Grant
    Participant

    It looks like Dan has the correct response here. Either one of his replies should work on Windows 8.1 and up or Server 2012 and up. To do the second one on a remote computer, You can do this:

    Invoke-Command -ComputerName PCNameHere -ScriptBlock {[bool]((Get-NetFirewallProfile -name domain).enabled -eq 'True')}
    

    The first solution you posted looks like it gets all firewall rules and not just if the Firewall is enabled or not. One thing to be sure of before you start building a script is to make sure you are using the correct cmdlet. Start by getting the information you need first and then start to build the function.

  • #33005

    Ed O’Connor
    Participant

    Thank You all

You must be logged in to reply to this topic.