Home > OS >  Powershell script to send files in a folder to an API in alphabetical order
Powershell script to send files in a folder to an API in alphabetical order

Time:11-20

I struggle with my ps-script to send files from a folder to an API in alphabetical order. I also need to let the script sleep for 10 seconds after 2 files being sent. I am trying to send each file 100 x to this api, so that's why I used 1..100 there and using $command to see my progress, but that already works so that's why I didn't post the rest of my script.

Any help is appriciated, I came up with this:

$url = "https://anywebserver"    
$localfolder = "c:\folder"
Set-Location $localfolder
$localfiles = Get-ChildItem $localfolder | Sort-Object -Descending

$count=0
ForEach ($LocalFile in $localfiles) 
{
    if(  $count %2 eq 0)
    { 
        Start-Sleep -Seconds 10 
    }
    $command = [scriptblock]{(1..100|%{result = Invoke-RestMethod -Method Post -InFile "$LocalFile -Uri $url;})}
}

CodePudding user response:

Hopefully the following is helpful in showing how to take 2 files at a time in alphabetical order. I've changed the 1..100 to 1..2 and the sleep to 1 second for speed of testing, these can obviously be changed to your preferred values.

$skip = 0
$copy = 1

$path = "c:\folder"

while(gci $path | ?{! $_.PSIsContainer} | sort Name | select -skip $skip | select -first 2){
    
    $filesToCopy = gci $path | ?{! $_.PSIsContainer} | sort Name | select -skip $skip | select -first 2
    
    1..2 | %{
    
        #Perform copy
        $filesToCopy
        write-output "Copy Number $copy Complete"
        Start-Sleep 1
    }

    $skip = $skip   2
    $copy  

}

CodePudding user response:

Your Start-Sleep is running outside of the loop which is writing the data., so all it's doing is sleeping, then running all one hundred POST requests with no Sleep inbetween them. You want something more like this:

$url = "https://anywebserver"    
$localfolder = "c:\folder"
Set-Location $localfolder
$localfiles = Get-ChildItem $localfolder | Sort-Object -Descending

$count=0
ForEach ($LocalFile in $localfiles) 
{
    $command = [scriptblock]{
        For($i=1;$i -le 100;$i  ){
            result = Invoke-RestMethod -Method Post -InFile $LocalFile -Uri $url;
            if(($i % 2) -eq 0){Start-Sleep -Seconds 10}
        })
    }
}
  • Related