The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,947 other followers

Archive for the ‘PowerShell’ Category

PowerShell: working around Get-NetFirewallRule not showing all the fields that Set-NetFirewallRule allows you to set

Posted by jpluimers on 2022/10/26

With APIs, you always hope that Get and Set methods mirror each other. More often than not, they don’t.

Take for instance these two:

They are far from symmetric: [Wayback/Archive] Get-NetFirewallRule shows far less than [Wayback/Archive] Set-NetFirewallRule allows you to set (first and foremost the various port related properties). It can be worked around though.

There are a few posts discussing this, of which I think these two are the most important:

Both above posts via [Wayback/Archive] “Get-NetFirewallRule” “LocalPort” – Google Search.

This is what I was after:

PowerShell "Get-NetFirewallRule -Name 'RemoteDesktop-UserMode-In-TCP' | Select-Object Name,DisplayName,Enabled,Direction,@{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},Action,@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}}"

Or actually:

PowerShell "Get-NetFirewallRule -Name 'RemoteDesktop-UserMode-In-TCP' -ErrorAction SilentlyContinue | Select-Object Name,DisplayName,Enabled,Direction,@{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},Action,@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}}"

Let me explain this:

  1. Get-NetFirewallRule gets a firewall rule with a specific name, but can only get you a few properties that can be set through Set-NetFirewallRule. Name,DisplayName,Enabled,Direction are properties it understands. Protocol and LocalPort aren’t, but are often of interest.
  2. Get-NetFirewallPortFilter can get you both Protocol and LocalPort.
  3. There are more functions named like Get-NetFirewall*Filter, all of which require an -AssociatedNetFirewallRule <CimInstance> (or an -All) parameter which is what Get-NetFirewallRule returns. This way you can retrieve details not provided by Get-NetFirewallRule.
  4. The portions like @{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}} returns one property, in this case the Protocol property from Get-NetFirewallPortFilter returned as Protocol (the latter can be different if you want; the former needs to be Protocol).
  5. The -ErrorAction SilentlyContinue bit is to prevent this kind of exception when no -Name matches:
    Get-NetFirewallRule : No MSFT_NetFirewallRule objects found with property 'InstanceID' equal to
    'RemoteDesktop-UserMode-In-TCP_'.  Verify the value of the property and retry.
    At line:1 char:1
    + Get-NetFirewallRule -Name 'RemoteDesktop-UserMode-In-TCP_'
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (RemoteDesktop-UserMode-In-TCP_:String) [Get-NetFirewallRule], CimJobExc
       eption
        + FullyQualifiedErrorId : CmdletizationQuery_NotFound_InstanceID,Get-NetFirewallRule
    When the exception occurs, the execution continues, but since no object is returned the | pipe will not execute and no details are returned.

    I got this trick from [Wayback/Archive] firewall – How can I stop the Powershell command `Get-NetFirewallRule` from throwing an error? – Stack Overflow (thanks [Wayback/Archive] Pure.Krome and [Wayback/Archive] arco444)

Notes:

  • 3. also allows Get-NetFirewallRule to search for a group, then get all the firewall rules out of them, for instance with
    Get-NetFirewallRule -DisplayGroup "File and Printer Sharing" | ForEach-Object { Write-Host $_.DisplayName ; Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $_ }
  • 4. also works the other way around, but only if you have elevated using an administrative token. The below lists all firewall rules involving port 3389 (Remote Desktop Protocol):
    PowerShell "Get-NetFirewallPortFilter | Where LocalPort -eq 3389 | Get-NetFirewallRule"

    Even a plain Get-NetFirewallPortFilter will get you an error without elevation:

    Get-NetFirewallPortFilter : Access is denied.
    At line:1 char:1
    + Get-NetFirewallPortFilter
    + ~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (MSFT_NetProtocolPortFilter:root/standardci...tocolPortFilter) [Get-Ne
       tFirewallPortFilter], CimException
        + FullyQualifiedErrorId : Windows System Error 5,Get-NetFirewallPortFilter

You might want to return more details than just Protocol and Localport, so I dug around and made the below table to document the asymmetry.

Read the rest of this entry »

Posted in CommandLine, Development, Power User, PowerShell, PowerShell, Remote Desktop Protocol/MSTSC/Terminal Services, Scripting, Software Development, Windows | Leave a Comment »

Hardware MAC address formats (which I need for Wake-on-LAN.ps1)

Posted by jpluimers on 2022/07/06

Early june, I blogged about Wake-on-LAN from a Windows machine.

My plan was to adopt [Wayback/Archive.is] Wake.ps1 into Wake-on-LAN.ps1 (as naming is important).

One of the goals was to support multiple hardware MAC address formats, especially as Wake.ps1 had the below comment, but did support the AA-BB-CC-DD-EE-FF, though not the AA:BB:CC:DD:EE:FF hardware MAC address format:

<#
...
.NOTES
Make sure the MAC addresses supplied don't contain "-" or ".".
#>

A colon separated hardware MAC address would result in this error inside the call to the [Wayback/Archive.is] PhysicalAddress.Parse Method (System.Net.NetworkInformation) | Microsoft Docs:

Send-Packet : Exception calling "Parse" with "1" argument(s): "An invalid physical address was specified."

So I did some digging, starting inside the above mentioned blog post, and adding more:

  1. Wake.ps1 uses the [Wayback/Archive.is] Parse method in the [Wayback/Archive.is] PhysicalAddress.cs source code in C# .NET,  which contains code like this:
                //has dashes? 
                if (address.IndexOf('-') >= 0 ){ 
                    hasDashes = true;
                    buffer = new byte[(address.Length+1)/3]; 
                }
  2. The Perl script at [Wayback/Archive.is] wakeonlan/wakeonlan at master · jpoliv/wakeonlan that started my first blog post in this series which mentions:
    • xx:xx:xx:xx:xx:xx (canonical)
    • xx-xx-xx-xx-xx-xx (Windows)
    • xxxxxx-xxxxxx (Hewlett-Packard switches)
    • xxxxxxxxxxxx (Intel Landesk)

    I should rename the first one IEEE 802, as per this:

  3. The MAC address: Notational conventions – Wikipedia

    The standard (IEEE 802) format for printing EUI-48 addresses in human-friendly form is six groups of two hexadecimal digits, separated by hyphens (-) in transmission order (e.g. 01-23-45-67-89-AB). This form is also commonly used for EUI-64 (e.g. 01-23-45-67-89-AB-CD-EF).[2] Other conventions include six groups of two hexadecimal digits separated by colons (:) (e.g. 01:23:45:67:89:AB), and three groups of four hexadecimal digits separated by dots (.) (e.g. 0123.4567.89AB); again in transmission order.[30]

    The latter is used by Cisco (see for instance [Wayback/Archive.is] Cisco DCNM Security Configuration Guide, Release 4.0 – Configuring MAC ACLs [Support] – Cisco and [Wayback/Archive.is] Cisco IOS LAN Switching Command Reference – mac address-group through revision [Support] – Cisco), so another format to add:

    • xxxx.xxxx.xxxx (Cisco)
  4. [Wayback/Archive.is] PhysicalAddress.Parse Method (System.Net.NetworkInformation) | Microsoft Docs remarks:

    The address parameter must contain a string that can only consist of numbers and letters as hexadecimal digits. Some examples of string formats that are acceptable are as follows:

    • 001122334455
    • 00-11-22-33-44-55
    • 0011.2233.4455
    • 00:11:22:33:44:55
    • F0-E1-D2-C3-B4-A5
    • f0-e1-d2-c3-b4-a5

    Use the GetAddressBytes method to retrieve the address from an existing PhysicalAddress instance.

  5. After a bit more digging via [Wayback/Archive.is] “three groups of four hexadecimal digits separated by dots” – Google Search , I found that even more hardware MAC address formats are in use as per [Wayback/Archive.is] What are the various standard and industry practice ways to express a 48-bit MAC address? – Network Engineering Stack Exchange.

    I really do not have all the sources for the various representations for 48-bit MAC addresses, but I have seen them variously used:

    AA-BB-CC-DD-EE-FF
    AA.BB.CC.DD.EE.FF
    AA:BB:CC:DD:EE:FF
    AAA-BBB-CCC-DDD
    AAA.BBB.CCC.DDD
    AAA:BBB:CCC:DDD
    AAAA-BBBB-CCCC
    AAAA.BBBB.CCCC
    AAAA:BBBB:CCCC
    AAAAAA-BBBBBB
    AAAAAA.BBBBBB
    AAAAAA:BBBBBB

From the last list, which is far more complete than the others, I recognise quite a few from tools I used in the past, but too forgot the actual sources, so I took the full list from there and tried to name them in parenthesis after the links I found above and what I remembered:

  • AABBCCDDEEFF (Bare / Landesk)
  • AA-BB-CC-DD-EE-FF (IEEE 802 / Windows)
  • AA.BB.CC.DD.EE.FF (???)
  • AA:BB:CC:DD:EE:FF (Linux / BSD / MacOS)
  • AAA-BBB-CCC-DDD (???)
  • AAA.BBB.CCC.DDD (Cisco?)
  • AAA:BBB:CCC:DDD (???)
  • AAAA-BBBB-CCCC (???)
  • AAAA.BBBB.CCCC (Cisco / Brocade)
  • AAAA:BBBB:CCCC (???)
  • AAAAAA-BBBBBB (Hewlett-Packard networking)
  • AAAAAA.BBBBBB (???)
  • AAAAAA:BBBBBB (???)

Some additional links in addition to the ones above:

–jeroen

Posted in .NET, CommandLine, Development, Encoding, HEX encoding, Network-and-equipment, Power User, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »

chocolatey-community/chocolatey-test-environment: A testing setup related to how the Chocolatey Package Verifier runs testing. Used for manual testing or prior to submission

Posted by jpluimers on 2022/06/29

On my list of things to play around with: [Wayback/Archive.is] chocolatey-community/chocolatey-test-environment: A testing setup related to how the Chocolatey Package Verifier runs testing. Used for manual testing or prior to submission

It sort of is a standalone version of the [Wayback] Chocolatey Software Docs | Package Verifier Moderation Service that you can use to check Chocolatey package that you develop/modify.

From the github repository README:

Requirements

You need a computer with:

  • a 64-bit processor and OS
  • Intel VT-x enabled (usually not an issue if your computer is newer than 2011). This is necessary because we are using 64bit VMs.
  • Hyper-V may need to be disabled for Virtualbox to work properly if your computer is a Windows box. NOTE: This may actually not be required.
  • At least 10GB of free space.

Setup

To get started, ensure you have the following installed:

  • Vagrant 1.8.1+ – linked clones is the huge reason here. You can technically use any version of Vagrant 1.3.5+. But you will get the best performance with 1.8.x+. It appears you can go up to Vagrant 2.1.5, but may have some issues with 2.2.2 and Windows guests (newer versions may be fine).
  • Virtualbox 4.3.28+ – 6.1.6 (this flows in the selection of Vagrant – 5.2.22 seems to have some issues but newer versions may work fine)
  • vagrant sahara plugin (vagrant plugin install sahara)

NOTE: If you decide to run with version 1.8.1 of Vagrant, you are going to need to set the VAGRANT_SERVER_URL environment variable as described in this forum post, otherwise, you will get an HTTP 404 error when attempting to download the base vagrant box used here.

Related: people wanting to do a similar thing for Linux: [Archive.is] chocolatey/choco: Has anyone ever tried to set up virtual box with linux (e.g. ubuntu) for choco testing ? – Gitter

Yes, it should work for choco newchoco pack, and choco push, running on mono.
[Wayback/Archive.is] https://github.com/chocolatey/choco/runs/3660684196?check_suite_focus=true

There is also a dockerfile available here:
[Wayback/Archive.is] https://github.com/chocolatey/choco/tree/develop/docker

However, as @AdmiringWorm said, there are not any official builds or official support at this time.

In my own private fork of choco however I’m using such interfaces as RestartManager

    //https://docs.microsoft.com/en-us/windows/win32/api/restartmanager/nf-restartmanager-rmstartsession
    [DllImport("rstrtmgr.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle,
                                     int dwSessionFlags,
                                     string strSessionKey);

    //https://docs.microsoft.com/en-us/windows/win32/api/restartmanager/nf-restartmanager-rmendsession
    [DllImport("rstrtmgr.dll", SetLastError = true)]
    static extern int RmEndSession(uint pSessionHandle);

    //https://docs.microsoft.com/en-us/windows/win32/api/restartmanager/nf-restartmanager-rmgetlist
    [DllImport("rstrtmgr.dll", SetLastError = true)]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] ProcessInfo[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

those will be windows specific indeed, but I’ll reach them later on.

Tarmo Pikaro

–jeroen

Posted in .NET, Chocolatey, CommandLine, Development, Power User, PowerShell, PowerShell, Scripting, Software Development, Windows | Leave a Comment »

How can you export the Visual Studio Code extension list? (via: Stack Overflow)

Posted by jpluimers on 2022/06/16

Adapted from [Archive.is] How can you export the Visual Studio Code extension list? – Stack Overflow, presuming that code is on the PATH:

  1. From the command-line interface on MacOS, Linux, BSD or on Windows with git installed:
    code --list-extensions | xargs -L 1 echo code --install-extension
  2. From the command-line interface on MacOS, Linux, BSD or on Windows without git installed:
    code --list-extensions | % { "code --install-extension $_" }

    or, as I think, more clearly (see also [WayBack] syntax – What does “%” (percent) do in PowerShell? – Stack Overflow):

    code --list-extensions | foreach { "code --install-extension $_" }

    or even more explanatory:

    code --list-extensions | ForEach-Object { "code --install-extension $_" }
  3. From the command-line interface on Windows as a plain cmd.exe command:
    @for /f %l in ('code --list-extensions') do @echo code --install-extension %l
  4. On Windows as a plain cmd.exe batch file (in a .bat/.cmd script):
    @for /f %%l in ('code --list-extensions') do @echo code --install-extension %%l
  5. The above two on Windows can also be done using PowerShell:
    PowerShell -Command "code --list-extensions | % { """""code --install-extension $_""""" }"

    Note that here too, the % can be expanded into foreach or ForEach-Object for clarity.

All of the above prepend “code --install-extension ” (note the trailing space) before each installed Visual Studio Code extension.

They all give you a list like this which you can execute on any machine having Visual Studio Code installed and its code on the PATH, and a working internet connection:

code --install-extension DavidAnson.vscode-markdownlint
code --install-extension ms-vscode.powershell
code --install-extension yzhang.markdown-all-in-onex

(This is about the minimum install for me to edit markdown documents and do useful things with PowerShell).

Of course you can pipe these to a text-file script to execute them later on.

The double-quote escaping is based on [Wayback/Archive.is] How to escape PowerShell double quotes from a .bat file – Stack Overflow:

you need to escape the " on the command line, inside a double quoted string. From my testing, the only thing that seems to work is quadruple double quotes """" inside the quoted parameter:

powershell.exe -command "echo '""""X""""'"

Via: [Archive.is] how to save your visual studio code extension list – Google Search

–jeroen

Posted in *nix, *nix-tools, .NET, bash, Batch-Files, CommandLine, Console (command prompt window), Development, Mac OS X / OS X / MacOS, Power User, PowerShell, PowerShell, Software Development, Visual Studio and tools, vscode Visual Studio Code, Windows, Windows 10, Windows 7, Windows 8, Windows 8.1, Windows Development, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012, Windows Server 2012 R2, Windows Server 2016, WSL Windows Subsystem for Linux, xargs | Leave a Comment »

Chocolatey on Windows 7: “You must provide a value expression on the right-hand side of the ‘-‘ operator.”

Posted by jpluimers on 2022/06/08

One of the places explaining a more and more frequent error on Windows 7 installations is [Wayback/Archive.is] “You must provide a value expression on the right-hand side of the ‘-‘ operator.” · Issue #29 · shiftkey/chocolatey-beyondcompare:

Read the rest of this entry »

Posted in Chocolatey, CommandLine, Development, Microsoft Surface on Windows 7, Power User, PowerShell, PowerShell, Scripting, Software Development, Windows, Windows 10, Windows 7, Windows 8, Windows 8.1, Windows Server 2003, Windows Server 2003 R2, Windows Server 2008, Windows Server 2008 R2 | Leave a Comment »

 
%d bloggers like this: