gpt4 book ai didi

正则表达式 IF 条件

转载 作者:行者123 更新时间:2023-12-01 14:56:17 27 4
gpt4 key购买 nike

我正在寻找一种方法来过滤我的主机文件中的新 IP 地址。我创建了一个脚本,每次我用来自矩阵企业管理器的数据调用它时都会更新我的主机文件。它工作正常。但是我必须找到一个解决方案,只允许更新 10.XX.XX.XX 或 172.XX.XX.XX 地址。

Param(
$newHost = $args[0],
$newIP = $args[1]
)

$SourceFile = "hosts"
$Match = "$newHost"

(Get-Content $SourceFile) | % {if ($_ -notmatch $Match) {$_}} | Set-Content $SourceFile

Start-Sleep -Seconds 1

$tab = [char]9
$enter = $newIP + $tab + $newHost

if ($newIP XXXX) #--> here should be a regex if condition... no clue how it works..

$enter | Add-Content -Path hosts

最佳答案

您的代码过于复杂,没有正确使用 PowerShell 提供的功能。

  • 不要分配 $args[...]到参数。不是这样 parameter handling在 PowerShell 中工作。改为强制参数。
  • % {if ($_ -notmatch $Match) {$_}}更好地表述为 Where-Object {$_ -notmatch $Match} .
  • 如果 $Match是一个 FQDN,点可能会导致误报(因为它们匹配任何字符,而不仅仅是文字点)。要么逃脱$Match ( [regex]::Escape($Match) ) 或使用 -notlike运算符。
  • PowerShell 有一个用于制表符的转义序列 (`t)。无需定义值为 [char]9 的变量.
  • 将变量放在双引号字符串 ("$var1$var2") 中通常比字符串连接 ($var1 + $var2) 更具可读性。

把你的代码改成这样:

[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$Hostname,
[Parameter(Mandatory=$true)]
[string]$IPAddress
)

$SourceFile = 'hosts'

(Get-Content $SourceFile) |
Where-Object { $_ -notlike "*$Hostname*" } |
Set-Content $SourceFile

Start-Sleep -Seconds 1

if ($IPAddress -match '^(10|172)\.') {
"$IPAddress`t$Hostname" | Add-Content $SourceFile
}

如果要避免多次写入输出文件,可以将读取的数据收集到一个变量中,然后一次性写入该变量和新记录:

$hosts = @(Get-Content $SourceFile) | Where-Object { $_ -notlike "*$Hostname*" })

if ($IPAddress -match '^(10|172)\.') {
$hosts += "$IPAddress`t$Hostname"
}

$hosts | Set-Content $SourceFile

您可以通过 parameter validation 进行检查来进一步优化您的脚本, 所以你不需要 if首先是函数体中的条件,例如像这样:

Param(
[Parameter(Mandatory=$true)]
[string]$Hostname,
[Parameter(Mandatory=$true)]
[ValidatePattern('^(10|172)\.')]
[string]$IPAddress
)

或者像这样:

Param(
[Parameter(Mandatory=$true)]
[string]$Hostname,
[Parameter(Mandatory=$true)]
[ValidateScript({$_ -match '^(10|172)\.' -and [bool][ipaddress]$_})]
[string]$IPAddress
)

关于正则表达式 IF 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44430539/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com