我需要有关Powershell脚本的帮助,该脚本从文本文件读取指定行,并使用txtfile中的值创建一个新变量。变量名应为$ var1,值应为$ var2。
新创建的变量中的值应该是这样
$number = 4
$Computername = "Test123$number"
$txt = Get-Content -Path .xyz.txt | Where-Object {$_ -like '@set*'}
foreach ($line in $txt){
$firstclip=$line.IndexOf("(")
$delimiter=$line.IndexOf(",")
$lastclip=$line.IndexOf(")")
$var1=$line.Substring($firstclip+1,$delimiter - ($firstclip + 1))
$var2=$line.Substring($delimiter+1,$lastclip - ($delimiter + 1))
$var2=$var2 -replace '%([^-]+)%','$$$1'
Write-Host $var1
Write-host $var2
#New-Variable -Name $var1 -Value $var2
}
TXT文件.xyz.txt
的内容:
@Set(DeviceID, 11)
@Set(ComputerName, PC-Name-%DeviceID%)
@Set(Nic0Name, LAN)
@Set(Nic0Ip, 10.42.50.101)
@Set(Nic0Mask, 255.255.255.0)
@Set(Nic0Gateway, 10.42.50.50)
@Set(AmsNetId, %Nic0Ip%.1.1)
@Set(AmsRoute0Name, PC-NAME-01)
@Set(AmsRoute0Ip, 10.42.50.51)
@Set(AmsRoute0AmsNetId, %AmsRoute0Ip%.1.1)
@Set(VAS, 10.42.50.42)
@Set(IEHomePage, http://%VAS%/web/PC-0%DeviceID%.html)
@Set(IEPath, "C:\Program Files\Internet Explorer\iexplore.exe")
实际上,值是Test123 $ number,因此Powershell不会将$ number转换为之前在变量中声明的数字。
答案 0 :(得分:0)
我将-split
运算符与备用字符一起使用来处理输入行,
并使用if
和RegEx检查是否有%var%替换为当前$ var内容。
编辑:为了更好地可视化更改,请输出[PSCustomObject]
EDIT2:需要使用-AllMatches切换到Select-String
## Q:\Test\2019\05\20\SO_56218447.ps1
$txt = Get-Content -Path .xyz.txt | Where-Object {$_ -like '@set*'}
$RE = '%([^%]+)%'
foreach ($line in $txt){
$Name,$Value = ($line -split '\(|\)|, ')[1,2]
$NewValue = $Value
($Value)|Select-String -Pattern $RE -AllMatches | ForEach-Object {$_.Matches}|ForEach-Object{
$NewValue = $NewValue -replace $_.value,(Get-Variable -Name $_.value.Trim('%')).Value
}
New-Variable -Name $Name -Value $NewValue
[PSCustomObject]@{
Variable = $Name
Value = $Value
NewValue = $NewValue
}
}
样本输出
> Q:\Test\2019\05\20\SO_56218447.ps1
Variable Value NewValue
-------- ----- --------
DeviceID 11 11
ComputerName PC-Name-%DeviceID% PC-Name-11
Nic0Name LAN LAN
Nic0Ip 10.42.50.101 10.42.50.101
Nic0Mask 255.255.255.0 255.255.255.0
Nic0Gateway 10.42.50.50 10.42.50.50
AmsNetId %Nic0Ip%.1.1 10.42.50.101.1.1
AmsRoute0Name PC-NAME-01 PC-NAME-01
AmsRoute0Ip 10.42.50.51 10.42.50.51
AmsRoute0AmsNetId %AmsRoute0Ip%.1.1 10.42.50.51.1.1
VAS 10.42.50.42 10.42.50.42
IEHomePage http://%VAS%/web/PC-0%DeviceID%.html http://10.42.50.42/web/PC-011.html
IEPath "C:\Program Files\Internet Explorer\iexplore.exe" "C:\Program Files\Internet Explorer\iexplore.exe"