【发布时间】:2021-11-05 19:18:12
【问题描述】:
首先在这里尝试使用 powershell - 我有一个像这样格式化的 CSV。
IPAddress,Username,Password
11.11.34.48,user,pass
我想使用 Powershell 循环遍历 CSV 的每一行并构建一个 URL,然后我会调用它。
$path = "D:\Users\user\Documents\DeviceFocus.csv"
$ValidHeaders = @(
"IPAddress",
"Username",
"Password"
)
try {
$DeviceList = @(Import-Csv $path)
$CSVHeaders = $DeviceList | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name
foreach ($Header in $ValidHeaders) {
if ($CSVHeaders -notcontains $Header) {
throw [System.Management.Automation.PropertyNotFoundException] "CSV file does not contain a correct header row."
}
else {
##echo $DeviceList
}
}
}
catch [Exception] {
$msg = "Failed to import CSV file $CSVFile. Detailed Exception Trace - " + $_.Exception.Message + "`r`n"
throw $msg
}
## Setup Counter
$Count = 0
$MaxFailureCount = 3
$FailureCount = 0
$CountBegin = $CameraList.Count
while ($Count -lt $CountBegin) {
if ($FailureCount -gt $MaxFailureCount) {
break
}
$Count++
ForEach-Object {
{
Invoke-WebRequest -Uri "http://$($_.Username):$($_.Password)@$($_.IPAddress)/rcp.xml?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001"
}
}
}
if ($FailureCount -gt $MaxFailureCount) {
echo "Maximun number of failures has been reached. Halting execution."
Write-Host "Please check your CSV file for errors and ensure your are running in a new powershell session." -BackgroundColor Yellow -ForegroundColor Red
break
}
else {
echo "Done2"
}
一个问题阻止了Invoke-WebRequest 我得到一个错误:
Invoke-WebRequest : Cannot bind parameter 'Uri'. Cannot convert value "http://:@/rcp.xml?command=0x09a5&type=P_OCTET&direction=WRITE&num=1&payload=0x85000401c9020001" to type "System.Uri". Error: "Invalid URI: The
hostname could not be parsed."
At line:1 char:25
+ ... equest -Uri "http://$($_Username):$($_Password)@$($_IPAddress)/rcp.xm ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
网址不包含来自 CSV 文件的三个参数IPAddress、username、Password。为什么不呢?
【问题讨论】:
标签: powershell loops csv foreach invoke-webrequest