【问题标题】:How can I get the foreach to work in my code如何让 foreach 在我的代码中工作
【发布时间】:2015-11-11 15:52:39
【问题描述】:

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

【问题讨论】:

    标签: powershell powershell-4.0 powershell-ise


    【解决方案1】:

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

    【讨论】:

    • 我已经用您的更改测试了我的脚本的这种变体,现在 $file 变量已经存储了各种 txt 文件,无论出于何种原因,我无法弄清楚它为什么或如何拾取这些不存在的文件
    • @LeandreFouche 我不关注。 “已存储各种txt文件”是什么意思? ForEach-Object 循环遍历 Get-ChildItem 生成的文件。每次迭代$file 包含当前文件名。
    • 它清除了,我不知道为什么它会拾取文件位置中未包含的不同文本文件
    【解决方案2】:
    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"}
      

    【讨论】:

    • 在 PowerShell 中使用变量 $path 没有错。没有具有该名称的automatic variable,也不能与PATH 环境变量混淆,因为后者是$env:Path
    【解决方案3】:

    类似的东西,虽然我无法真正测试它。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-24
      • 2020-09-15
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多