在将命令的输出通过管道传输到 csv 时,我正在尝试添加其他列。
我正在运行的命令是这样的:
Invoke-RestMethod -Uri $uri"<Request><Login><Username>admin</Username><Password>admin</Password></Login><Set operation='add'><IPHost><Name>$Name</Name><IPFamily>IPv4</IPFamily><HostType>IP</HostType><IPAddress>$IPAddress</IPAddress></IPHost></Set></Request>" | Select-Object -Expand Response | Select-Object -Expand IPHost | Select-Object -Expand Status | Export-csv -Append -Path "C:\Powershell\output.csv"
我在output.csv中得到如下输出;
"code","#text"
"200","Configuration applied successfully."
我想在第 3 列和第 4 列中附加$Name 和 $IPAddress的值,但我不知道该怎么做。
编辑-
我希望它看起来像;
"code","#text"
"200","Configuration applied successfully.","Server 1","192.168.1.1"
(为这些列添加标题并不重要)
Edit2 - 我将在这里扩展我的解释。代码是通过 API 将主机列表添加到防火墙,这是完整的脚本;
$csv = import-csv C:\Powershell\network.csv
$uri = "https://172.16.16.16:4444/webconsole/APIController?reqxml="
$csv | ForEach-Object {
$Name = $_.name
$IPAddress =$_.ipaddress
Invoke-RestMethod -Uri $uri"<Request><Login><Username>admin</Username><Password>admin</Password></Login><Set operation='add'><IPHost><Name>$Name</Name><IPFamily>IPv4</IPFamily><HostType>IP</HostType><IPAddress>$IPAddress</IPAddress></IPHost></Set></Request>" | Select-Object -Expand Response | Select-Object -Expand IPHost | Select-Object -Expand Status Name, IPAddress | Export-csv -Append -Path "C:\Powershell\output.csv" -NoTypeInformation
}
如果我要直接运行原始请求,我会这样做;
https://172.16.16.16:4444/webconsole/APIController?reqxml=<Request><Login><Username>admin</Username><Password>admin</Password></Login><Set operation="add"><IPHost><Name>Server1</Name><IPFamily>IPv4</IPFamily><HostType>IP</HostType><IPAddress>192.168.1.1</IPAddress></IPHost></Set></Request>
在浏览器中,它给了我以下(XML)输出;
<Response APIVersion="1700.1">
<Login>
<status>Authentication Successful</status>
</Login>
<IPHost transactionid="">
<Status code="200">Configuration applied successfully.</Status>
</IPHost>
</Response>
当我通过 Invoke-RESTMethod 运行它时,我在 powershell 控制台中得到以下信息;
xml Response
--- --------
version="1.0" encoding="UTF-8" Response
PS C:\powershell>
Select-Object 命令的每次迭代都会扩展,直到达到结果
Select-Object -Expand Response
给;
APIVersion Login IPHost
---------- ----- ------
1700.1 Login IPHost
PS C:\powershell>
和
Select-Object -Expand Response | Select-Object -Expand IPHost
给;
transactionid Status
------------- ------
Status
PS C:\powershell>
最后是完整的命令;
Select-Object -Expand Response | Select-Object -Expand IPHost | Select-Object -Expand Status
给;
code #text
---- -----
200 Configuration applied successfully.
对于每个主机,这是我想要的(即操作的结果)。然后我只想将它导出到一个输出文件,但也有指示该状态适用于哪个 IP 主机。我认为 CSV 是最简单的格式,但也许不是?
希望这更清楚!