将变量传递给函数失败
问题描述:
我正在PowerShell中编写一个函数,使用他的API从PHP-IPAM获取IP。将变量传递给函数失败
我的功能看起来像;
function Get-IP($IPAM_Space, $IPAM_customer) {
Write-Host $IPAM_Space
Write-Host $IPAM_customer
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("Authorization", 'Basic ZGF2ZS5ncmVlYmU6RGF2MWRzb24=')
$GetToken = Invoke-RestMethod $IPAM_URL/api/VMDeploy/user/ -Method Post -Headers $Headers
$token = $GetToken.data.token
$Headers.Add("token", $token)
$All_sections = Invoke-RestMethod $IPAM_URL/api/VMDeploy/sections/ -Method Get -Headers $Headers
$Space_Section_details = $All_sections.data | where Name -eq "$IPAM_Space"
$Space_id = $Space_Section_details.id
$Space_Subnets = Invoke-RestMethod $IPAM_URL/api/VMDeploy/sections/$Space_id/subnets/ -Method Get -Headers $Headers
$Customer_Subnet_details = $Space_Subnets.data | where "description" -eq "$IPAM_customer"
IF (!($Customer_Subnet_details)) {
$ErrorMessage = "$IPAM_customer in unknown in PHP-IPAM, fix that first"
SendErrorMail($ScriptName, $ErrorMessage)
throw
}
$Customer_Subnet_id = $Customer_Subnet_details.id
$Customer_IP_details = Invoke-RestMethod $IPAM_URL/api/VMDeploy/subnets/$Customer_Subnet_id/addresses/ -Method Get -Headers $Headers
$FreeAddress = Invoke-RestMethod $IPAM_URL/api/VMDeploy/subnets/$Customer_Subnet_id/first_free/ -Method Get -Headers $Headers
$netmask = $Customer_Subnet_details.mask
$gateway = ($Customer_IP_details.data) | where is_gateway -like '1' | Select -ExpandProperty IP
if (!($gateway)) {
$ErrorMessage = "$IPAM_customer in $IPAM_Space has no gateway setup in PHP-IPAM, fix that first"
SendErrorMail($ScriptName, $ErrorMessage)
throw
}
if ($IPAM_customer -ne "IS" -and $IPAM_customer -ne "Cogent") {
$InUse = Get-VMGuest -Vm "*$IPAM_customer*" | where IPAddress -like ($FreeAddress.data)
}
if (!($Inuse)) {
return ($FreeAddress.data), $netmask, $gateway
} else {
$Hostname = $InUse.HostName
$ErrorMessage = "$Address in use by $HostName"
SendErrorMail($ScriptName, $ErrorMessage)
throw
}
}
它做,当我这样称呼它负载:
Get-IP "Customers" "CustomerName"
该函数返回正确的信息。
问题在于,当我使用一个变量在我的调用函数:
Get-IP "Customers" "$CustomerName"
然后它挂在部分:
$Customer_Subnet_details = $Space_Subnets.data | where "description" -eq "$IPAM_customer"
if (!($Customer_Subnet_details)) {
$ErrorMessage = "$IPAM_customer in unknown in PHP-IPAM, fix that first"
SendErrorMail($ScriptName, $ErrorMessage)
throw
}
它告诉我,$IPAM_Customer
是找不到的。 奇怪的是,他是否输出了该变量的值。这也在write-host $IPAM_customer
中看到。
该函数仅在我使用Customer-name而不是使用变量内容进行硬编码时才起作用。
我也检查了什么类型的值是$IPAM_Customer
,这是一个字符串,所以也是好的。
我不知道为什么这样下去失败,所以我希望有人能告诉我这个(或劝我写我的功能有所不同。
答
我终于找到了答案。空格!....
最后一个电话在我的功能失效,$客户名称已配发白色的空间,我没有看到,不知道的..
我发现这样做;!
write-host "|$IPAM_customer|"
在我的脚本。 我看到| CustomerName |
我已经删除了空格手册,并且该函数工作的很棒!
请尝试像这样调用您的函数:'Get-IP -IPAM_Space“Customer”-IPAM_customer $ CustomerName' –
难道是'$ CustomerName'包含空白吗?你如何首先获得'$ CustomerName'? –
@MartinBrandl这也没有工作 $客户不包含空格。它是一个单词。我使用Excel获取我的$ CustomerName。 –