2015-08-18 205 views
1

我想获得多个文件输入到Invoke-WebRequest一个接一个地写入succuess或失败,取决于它是否有效。我怎样才能让我的代码工作在我的代码

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 
} 

回答

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

+0

我已经测试了你的改变我的脚本的这种变化,现在$文件变量已经存储了各种txt文件,为什么永远不会存在的原因,我无法弄清楚为什么或如何拿起这些不存在的文件 –

+0

@LeandreFouche我不'随后。你是什​​么意思“存储了各种txt文件”? 'ForEach-Object'循环遍历'Get-ChildItem'产生的文件。每次迭代'$ file'都包含当前的文件名。 –

+0

它清理了,我不知道为什么它拿起不包含在文件位置的不同文本文件 –

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 
} 
0
  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"} 
    
+1

在PowerShell中使用变量'$ path'没什么问题。这个名称没有[自动变量](https://technet.microsoft.com/en-us/library/hh847768.aspx),它也不能与PATH环境变量混淆,因为后者会是'$ env:Path'。 –

相关问题