1

I am using awk in Powershell , so I want to get the same result of what I get from a bash script. This awk Script is multiline, so I could do a separate file for the script such as firstScript.awk , but ultimately I want the Powershell Script to be able to contain that awk script (so not to clutter this with separate files)

I have succesfully done it with bash such as

firstScript='
$1 == "Default" && $2 == "Gateway" && $13 {
    for (i = 6; i > 1; i--) {
        if ( match(prev[i], /IPv4/) ) {
            print prev[i]
        }
    }
}
{
    for (i = 6; i > 1; i--) {
        prev[i] = prev[i - 1]
    }
    prev[1] = $0
}
'

awk "$firstScript" ./input.txt

This syntax does work for bash ( awk '$firstScript' ./input.txt would not work)

So I go now to Powershell and try to do the same, with the Powershell Escaping Characters considerations and other Syntax Considerations

$firstScript = @"
`$1 == "Default" && `$2 == "Gateway" && `$13 {
    for (i = 6; i > 1; i--) {
        if ( match(prev[i], /IPv4/) ) {
            print prev[i]
        }
    }
}
{
    for (i = 6; i > 1; i--) {
        prev[i] = prev[i - 1]
    }
    prev[1] = `$0
}
"@
ipconfig.exe | awk "$firstScript"

This wont work , wont show anything.

Whereas if I write a file such as firstScript.awk

$1 == "Default" && $2 == "Gateway" && $13 {
    for (i = 6; i > 1; i--) {
        if ( match(prev[i], /IPv4/) ) {
            print prev[i]
        }
    }
}
{
    for (i = 6; i > 1; i--) {
        prev[i] = prev[i - 1]
    }
    prev[1] = $0
}

Then call it from other file or directly in the prompt

PS > ipconfig.exe | awk -f firstScript.awk

It works

How could I correct the above Powershell script to parse the variable properly as an outter file awk script?

2
  • 1
    The sad reality in Windows PowerShell and in PowerShell (Core) up to v7.2.x is that an extra, manual layer of \-escaping of embedded " characters is required in arguments passed to external programs. This is fixed in PowerShell v7.3+, with selective exceptions on Windows. See the linked duplicate for details. Commented Nov 15, 2023 at 18:17
  • 2
    Aside from that you can use a single-quoted here-string to avoid the need to escape $ characters as `$ Commented Nov 15, 2023 at 18:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.