PSA:第一次使用PowerShell,我的首选对象是Bash或Python,如果看起来很怪异,则感到抱歉。
我创建了一个Powershell脚本,如果我们的Windows 2019 Server重新启动(例如powercut),它将检查Get-HnsNetwork | ? Name -eq "l2bridge"
是否返回。如果没有返回任何内容,则它将调用函数Create-Hns
,该函数创建一个External
和l2bridge
接口,然后将其与docker和kubernetes一起使用。下面是我到目前为止的代码。
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"
}
}
当我在Powershell中使用./Check-HnsNetwork.ps1
运行脚本时,它只是返回而不会注销到日志文件。根据VS代码,其格式正确。
上面的代码块我在做错什么吗?任何建议,将不胜感激。
只要这里不限制范围,就需要修复某些错误 邮政编码。如果$sFetch
从不求值为$false
或$null
,则错误不会在运行时出现。考虑以下内容:
Wrtie-Log -Entry $_
需要更改为Write-Log -Entry $_
If (!$sFetch) {
Write-Log -Entry "Didn't get any info on l2bridge, we need to create one."
Create-Hns
缺少结尾处的}