我正在尝试将多个文件逐个输入到Invoke-WebRequest
中,并根据它是否有效来编写succuess或failure。
Param(
[string]$path,
[string]$file,
[string]$spath
)
cls
$URI = "Link Can't be shown."
$path = "C:\Users\lfouche.ESSENCEHEALTH\Desktop\Monitoring Services and Sites\"
$spath = "C:\Users\lfouche.ESSENCEHEALTH\Desktop\txtFiles\"
$file = (Get-ChildItem 'C:\Users\lfouche.ESSENCEHEALTH\Desktop\Monitoring Services and Sites')
$inF = "$path" + "$file" + ".txt"
$otF = "$spath" + "$file"
foreach ($f in $file) {
wget $URI -Method post -ContentType "text/xml" -InFile $inF -OutFile $otF
}
if ($? -eq 'true') {
"Successful"
} else {
"Failure"
$LASTEXITCODE
}
答案 0 :(得分:2)
使用-ErrorAction Stop
将错误转换为终止错误,并在try
/ catch
块中捕获错误。
$path = 'C:\Users\lfouche.ESSENCEHEALTH\Desktop\Monitoring Services and Sites'
$spath = 'C:\Users\lfouche.ESSENCEHEALTH\Desktop\txtFiles'
Get-ChildItem $path | ForEach-Object {
$file = $_.Name
$inF = Join-Path $path "$file.txt"
$otF = Join-Path $spath $file
try {
Invoke-WebRequest $URI -Method post -ContentType "text/xml" -InFile $inF -OutFile $otF -ErrorAction Stop
"Success: $file"
} catch {
"Failure: $file"
$_.Exception.Message
}
}
我还建议使用ForEach-Object
循环而不是foreach
循环(请参阅上面的示例代码),这样您就可以使用连续的管道进一步处理输出。
答案 1 :(得分:0)
这些方面的东西,虽然我无法真正测试它。
Param(
[string]$path,
[string]$file,
[string]$spath
)
$URI = "Link Can't be shown."
$path = "C:\Users\lfouche.ESSENCEHEALTH\Desktop\Monitoring Services and Sites\"
$spath = "C:\Users\lfouche.ESSENCEHEALTH\Desktop\txtFiles\"
$files = (Get-ChildItem $path)
foreach ($f in $files) {
wget $URI -Method post -ContentType "text/xml" -InFile $f.FullName -OutFile $spath + $f.Name
}
if ($? -eq 'true') {
"Successful"
} else {
"Failure"
$LASTEXITCODE
}
答案 2 :(得分:0)
$path
的变量时要小心。我会避免它。如果要测试Invoke-WebRequest
(wget)cmdlet是否报告错误,请使用-ErrorVariable
参数存储任何错误,然后检查它是否为null。类似的东西:
Invoke-WebRequest -Uri "http://blabla" -ErrorVariable myerror
if ($myerror -ne $null) {throw "there was an error"}