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

时间:2015-08-18 15:48:39

标签: powershell powershell-v4.0 powershell-ise

我正在尝试将多个文件逐个输入到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 
}

3 个答案:

答案 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)

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

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