如何让 foreach 在我的代码中工作

How can I get the foreach to work in my code

我正在尝试将多个文件一个一个地输入到 Invoke-WebRequest 中,并根据它是否有效来写入成功或失败。

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 
}

类似的东西,虽然我不能真正测试它。

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
}
  1. 在 PowerShell 中使用名为 $path 的变量时要小心。我会避免它。
  2. 如果要测试 Invoke-WebRequest (wget) cmdlet 是否报告错误,请使用 -ErrorVariable 参数存储任何错误,然后检查它是否为空。类似于:

    Invoke-WebRequest -Uri "http://blabla" -ErrorVariable myerror
    if ($myerror -ne $null) {throw "there was an error"}
    

使用 -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 循环(参见上面的示例代码),这样您就可以使用连续管道进一步处理输出。