powershell - 奇怪的字符串问题
问题描述
我有一个很难描述的非常奇怪的问题,所以请多多包涵。
我有一个变量 $BestHost,它只包含一个 Windows 服务器的名称。我将此变量传递给我编写的名为 Get-CurrentSite 的模块,该模块进行一些测试以检查服务器所在的物理位置。
在测试中,我手动设置
PS C:\Windows\system32> $Besthost = "WK-VPS-009"
PS C:\Windows\system32> Get-CurrentSite -CHost $Besthost
WK
并且模块调用正常,给出了预期的结果。服务器位于站点 WK。
在较大的脚本中,$BestHost 由 API 调用定义,但结果相同。它读到
PS C:\Windows\system32> $BestHost = ($BestHost = Invoke-WebRequest -URI "http://hypervision.host.net/api/v1/vps/best_host?exclude=$currentsiteswap,$VPShost").Content
$BestHost= $BestHost -replace '"',"" #this just removes additional "
PS C:\Windows\system32> $BestHost
WK-VPS-009
但是当我这次尝试将此变量与 Get-CurrentSite 一起使用时,我得到了错误
PS C:\Windows\system32> Get-CurrentSite -CHost $BestHost
Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings.
At C:\Users\frank\Documents\WindowsPowerShell\Modules\Get-CurrentSite\Get-CurrentSite.psm1:10 char:12
+ $HostAdd = Invoke-Command -ComputerName $CHost { get-NetIPAddress}
这是 Invoke-Command 的错误,我首先使用 Get-CurrentSite 来确定站点位置。
我的第一个想法是变量类型,所以......
这是手动设置时的变量:
PS C:\Windows\system32> $BestHost.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
这是由 API 调用设置的:
PS C:\Windows\system32> $BestHost.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
对我来说,它们看起来是包含完全相同数据的相同变量,一个有效,一个无效。我很困惑。
任何帮助将不胜感激。
编辑:更多信息
我只是将这 2 个结果放入 2 个不同的变量中并比较它们并得到以下结果
PS C:\Windows\system32> $BestHost
WK-VPS-009
PS C:\Windows\system32> $BestHost1
WK-VPS-009
PS C:\Windows\system32> $BestHost1.Equals($BestHost)
False
PS C:\Windows\system32> ($BestHost.GetEnumerator() | % ToInt32 $null | % ToString X4) -join '-'
0057-004B-002D-0056-0050-0053-002D-0030-0030-0039
PS C:\Windows\system32> ($BestHost1.GetEnumerator() | % ToInt32 $null | % ToString X4) -join '-'
0057-004B-002D-0056-0050-0053-002D-0030-0030-0039-000A-000A
解决方案
看起来您的 API 函数以某种方式向字符串输出 (000A) 添加了两个换行符 在处理它之前,通过在代码中添加以下内容来清理这些换行符:
$besthost = $besthost -Replace '\x0A',''
您可以使用正则表达式 (regexp) 将该操作与双引号 (" ,ascii 代码 x22 ) 的清理结合起来:
$besthost = $besthost -Replace '[\x0A\x22]',''
推荐阅读
- nuget - 在 VSTS 发布期间将 NuGet 包部署到文件夹位置
- python - TypeError:不支持解码str(将字节转换为str)
- javascript - JavaScript 正则表达式解析 Latex \frac
- iis - 在 IIS 上运行 ASP Core 时出错
- c# - 2.2.1.0 中的自动映射器映射异常
- azure - Azure 服务定义 vmsize
- javascript - JS Date seconds 在 c# 中给出不同的日期
- typescript - 将响应数据转换为包含地图的类
- bash - 跨操作系统命令行工具的数据存储?
- python - 两个表的行级比较