Reputation: 33
I am trying to get multiple files to input into the Invoke-WebRequest
one by one and write succuess or failure depending if it works or not.
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
}
Upvotes: 1
Views: 134
Reputation: 200233
Use -ErrorAction Stop
to turn errors into terminating errors and catch them in a try
/catch
block.
$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
}
}
I would also recommend using a ForEach-Object
loop instead of a foreach
loop (see sample code above), so you can further process the output with a continued pipeline.
Upvotes: 2
Reputation: 825
Something along these lines, although I can't really test it.
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
}
Upvotes: 0
Reputation: 3341
$path
in PowerShell. I would avoid it.If you want to test whether the Invoke-WebRequest
(wget) cmdlet reported errors, use the -ErrorVariable
parameter to store any error and then check if it's null afterwards. Something like:
Invoke-WebRequest -Uri "http://blabla" -ErrorVariable myerror
if ($myerror -ne $null) {throw "there was an error"}
Upvotes: 0