PSA: First time I've used PowerShell, my go-to is Bash or Python, sorry if it looks weird.
I have created a Powershell script that, if our Windows 2019 Server reboots (powercut for example), it'll check to see if Get-HnsNetwork | ? Name -eq "l2bridge" returns. If there is nothing returned, it then calls the function Create-Hns which creates an External and l2bridge interface which is then used with docker and kubernetes. Below is the code tha I have so far.
function Write-Log {
param (
[Parameter(Mandatory=$False, Position=0)]
[String]$Entry
)
"$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff') $Entry" | Out-File -FilePath $LogFilePath -Append
}
Function Create-Hns {
Write-Log -Entry "Starting to create the HnsNetwork..."
Try {
ipmo c:\k\SDN\windows\helper.psm1 -force
ipmo c:\k\SDN\windows\hns.psm1 -force
if(!(Get-HnsNetwork | ? Name -eq "External")) {
New-HNSNetwork `
-Name "External" `
-Type NAT `
-AddressPrefix "192.168.x.x/30" `
-Gateway "192.168.x.x" `
-Verbose
}
if(!(Get-HnsNetwork | ? Name -eq "l2bridge")) {
New-HNSNetwork `
-Name l2bridge `
-Type L2Bridge `
-AddressPrefix "192.168.x.x/24" `
-Gateway "192.168.x.x" `
-Verbose
}
$hnsNetwork = Get-HnsNetwork | ? Name -eq l2bridge
$hnsEndpoint = New-HnsEndpoint `
-NetworkId ($hnsNetwork).Id `
-Name "l2bridge" `
-IPAddress "192.168.x.x" `
-Gateway "0.0.0.0" `
-Verbose Attach-HnsHostEndpoint `
-EndpointID ($hnsEndpoint).Id `
-CompartmentID 1
} Catch {
Write-Log -Entry "An error occured"
Write-Log -Entry $_
Break
}
If ($?) {
Write-Log -Entry "VERIFY HERE"
Wrtie-Log -Entry $_
}
}
$LogFilePath = "C:\k\CreateHns.log"
$sFetch = (Get-HnsNetwork | ? Name -eq "l2bridge")
If (!$sFetch) {
Write-Log -Entry "Didn't get any info on l2bridge, we need to create one."
Create-Hns
Else {
Write-Log -Entry "Got information for the l2bridge, nothing needs creating."
Write-Log -Entry "Nothing to do"
}
}
When I run the script with ./Check-HnsNetwork.ps1 in Powershell, it just returns and doesn't log out to the log file. According to VS code, it's formatted correctly.
Is there something I'm doing wrong with the above code block? Any advice would be appreciated.
As long as scoping is not an issue here, there are some errors in the posted code that need to be fixed. If $sFetch never evaluates to $false or $null, the errors do not present themselves at runtime. Consider the following:
Wrtie-Log -Entry $_ needs to be changed to Write-Log -Entry $_If (!$sFetch) { Write-Log -Entry "Didn't get any info on l2bridge, we need to create one." Create-Hns is missing the closing }