Adding an autoincrementing value to a string

I have a problem I was looking for help with.

Basically, I’m looking to add an auto-inceremnted value in to a string starting at 000 and incrementing by one each time a file is retrieved from an FTP server and placed in a local directory.

$MyCredential = Import-Clixml -Path 'C:\Cred\PW.txt'
$FTPServer = 'ftp://192.168.0.18'
$FTPPath = '/NatWest/L6XQ*.txt'
$LocalPath = "C:/Cred/L6XQ{0:MMdd}.txt" -f (get-date))
$CheckFile = 'C:/Cred/L6XQ*.txt'
$FileExists = Test-Path $CheckFile
Set-FTPConnection -Credentials $MyCredential -Server $FTPServer -Session FTPFileGetSession
$Session = Get-FTPConnection -Session FTPFileGetSession
Get-FTPChildItem -Session $Session -Path $FTPPath | Get-FTPItem -session $session -verbose -localpath $LocalPath
IF ($FileExists -eq $True)  {Get-FTPChildItem -Session $Session -Path /Natwest -Filter l6xq* | Remove-FTPItem -session $session -verbose}

I wanted to imbed the logic in to the following line of the above script

$LocalPath = "C:/Cred/L6XQ{0:MMdd}.txt" -f (get-date))

At the moment, this adds a month and day value to the filename as it places it in the local directory, but I want to include an auto incrementing value so the file looks like this instance

L6XQ3101.001.txt

I have tried placing a variable $NewNum in to some scripts blocks and then adding the ++ operator after -f, but this isn’t having the desired effect.

$StartNum = 000
$LocalPath = "C:/Cred/L6XQ{0:MMdd}.{1:$StartNum}.txt" -f (get-date), $StartNum ++)

Can anyone advise or point me in the right direction?

Try this

$StartNum = 0
$LocalPath = "C:/Cred/L6XQ{0:MMdd}.{1:000}.txt" -f (get-date), $StartNum++

In order to keep the number formatting with the leading zeros, you would want to do this:

if($StartNum -eq $null)
{
    $StartNum = 0
}

$StartNum++
$LocalPath = "C:/Cred/L6XQ{0:MMdd}.{1:000}.txt" -f (get-date), $StartNum.ToString("000")

First, you want to check if $StartNum is null. If yes, initialize it as 0. If it contains values, it will simply increment the number each time you run the script. The .ToString is adding leading zeros and defining how many total characters you have in the string.

Now this will work, but you would probably want to do a foreach loop. Also, keep in mind that you will only be able to increment the numbers in order if you keep the console or ISE open. As soon as it is gone from memory, you will start over again.

Hi Ed

This is great, thanks for the help. One thing though, the first increment that is added to the end of the file name is 003. What would I need to alter in the script to ensure this starts from 1?

Tha

Right I see. This value has incremented each time I’ve tested previously, which is why it sat at 3. I’ll create a new variable. Thanks again.

Will adding a ForEach loop enable the script to increase by one increment each time it’ run?

Ultimately, the script will run once an hour and should be conscious of any files that where obtained in the last run. So if 3 files where obtained from the FTP server in the last run, when the script next runs and grabs a file, it should have an increment value of 4.

Ideally, I want this increment to reset to 0 at the end of each day.

If you add the $StartNum++ in any type of loop, it will increment each time if runs through the loop. Ideally, you would get a list of files, do a foreach to name the file, move it elsewhere, then repeat for each item in the list. I’m not sure if the Get-FTPChildItem cmdlet (Function? I don’t see it defined) iterates through all files. If it does, then you don’t need a foreach, just a while loop.

As long as the variable ($StartNum) is still in memory, it will increment by one until the ISE or Shell closes. If you have this running as a scheduled task for example, it will start back at whatever you set $StartNum to since it will be a new PowerShell instance each time it is run. If you wanted to have it run every hour, you can have it sleep for one hour by adding

Start-Sleep -Seconds 3600

at the end of your outside of a while loop. It would look something like this:

while($true)
{

MyCredential = Import-Clixml -Path 'C:\Cred\PW.txt'
$FTPServer = 'ftp://192.168.0.18'
$FTPPath = '/NatWest/L6XQ*.txt'
if($StartNum -eq $null)
{
    $StartNum = 0
}

$StartNum++
$LocalPath = "C:/Cred/L6XQ{0:MMdd}.{1:000}.txt" -f (get-date), $StartNum.ToString("000")
$CheckFile = 'C:/Cred/L6XQ*.txt'
$FileExists = Test-Path $CheckFile
Set-FTPConnection -Credentials $MyCredential -Server $FTPServer -Session FTPFileGetSession
$Session = Get-FTPConnection -Session FTPFileGetSession
Get-FTPChildItem -Session $Session -Path $FTPPath | Get-FTPItem -session $session -verbose -localpath $LocalPath
IF ($FileExists -eq $True)  {Get-FTPChildItem -Session $Session -Path /Natwest -Filter l6xq* | Remove-FTPItem -session $session -verbose}


Start-Sleep -Seconds 3600
}

If Get-FTPChileItem doesn’t iterate through all items, can you show me the Function? We should be able to get it to work.

Thanks for your assictance. Really appreciate it. In terms of running the script every hours, but reseting the increments each day, this makes sense as I could configure a scheduled task to run the script each day, but put a condition in to kill the script at the end of each day.

I downloaded the PSFTP module which contains Get-FTPChildItem from the https://gallery.technet.microsoft.com/scriptcenter/ repository.

https://gallery.technet.microsoft.com/scriptcenter/PowerShell-FTP-Client-db6fe0cb

Did you want to see the help?

NAME
Get-FTPChildItem

SYNOPSIS
Gets the item and child items from ftp location.

SYNTAX
Get-FTPChildItem [[-Path] ] [[-Session] ] [-Recurse] [[-Depth] <Int
[[-Filter] ] [-WhatIf] [-Confirm]

DESCRIPTION
The Get-FTPChildItem cmdlet gets the items from ftp locations. If the item is a
container, it gets the items inside the container, known as child items.

PARAMETERS
-Path
Specifies a path to ftp location or file.

    Required?                    false
    Position?                    1
    Default value
    Accept pipeline input?       true (ByValue, ByPropertyName)
    Accept wildcard characters?  false

-Session 
    Specifies a friendly name for the ftp session. Default session name is
    'DefaultFTPSession'.

    Required?                    false
    Position?                    2
    Default value                DefaultFTPSession
    Accept pipeline input?       false
    Accept wildcard characters?  false

-Recurse []
    Get recurse child items.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       true (ByPropertyName)
    Accept wildcard characters?  false

-Depth 
    Define depth of  folder in recurse mode. Autoenable recurse mode.

    Required?                    false
    Position?                    3
    Default value                0
    Accept pipeline input?       false
    Accept wildcard characters?  false

-Filter 
    Specifies a filter parameter to return only this objects that have proper name.
    parameter allow to use of wildcards. Defalut value is *.

    Required?                    false
    Position?                    4
    Default value                *
    Accept pipeline input?       false
    Accept wildcard characters?  false

-WhatIf []

    Required?                    false
    Position?                    named
    Default value
    Accept pipeline input?       false
    Accept wildcard characters?  false

-Confirm []

    Required?                    false
    Position?                    named
    Default value
    Accept pipeline input?       false
    Accept wildcard characters?  false


    This cmdlet supports the common parameters: Verbose, Debug,
    ErrorAction, ErrorVariable, WarningAction, WarningVariable,
    OutBuffer and OutVariable. For more information, see
    about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

INPUTS

OUTPUTS
PSFTP.Item

NOTES

    Author: Michal Gajda
    Blog  : http://commandlinegeeks.com/

-------------------------- EXAMPLE 1 --------------------------

PS P:\&gt;Get-FTPChildItem -path ftp://ftp.contoso.com/folder


Parent: ftp://ftp.contoso.com/folder

Dir Right     Ln  User   Group  Size   ModifiedDate        Name
--- -----     --  ----   -----  ----   ------------        ----
d   rwxr-xr-x 3   ftp    ftp           2012-06-19 12:58:00 subfolder1
d   rwxr-xr-x 2   ftp    ftp           2012-06-19 12:58:00 subfolder2
-   rw-r--r-- 1   ftp    ftp    1KB    2012-06-15 12:49:00 textitem.txt





-------------------------- EXAMPLE 2 --------------------------

PS P:\&gt;Get-FTPChildItem -path ftp://ftp.contoso.com/folder -Filter "subfolder*"


Parent: ftp://ftp.contoso.com/folder

Dir Right     Ln  User   Group  Size   ModifiedDate        Name
--- -----     --  ----   -----  ----   ------------        ----
d   rwxr-xr-x 3   ftp    ftp           2012-06-19 12:58:00 subfolder1
d   rwxr-xr-x 2   ftp    ftp           2012-06-19 12:58:00 subfolder2





-------------------------- EXAMPLE 3 --------------------------

PS P:\&gt;Get-FTPChildItem -path folder -Recurse


Parent: ftp://ftp.contoso.com/folder

Dir Right     Ln  User   Group  Size   ModifiedDate        Name
--- -----     --  ----   -----  ----   ------------        ----
d   rwxr-xr-x 3   ftp    ftp           2012-06-19 12:58:00 subfolder1
d   rwxr-xr-x 2   ftp    ftp           2012-06-19 12:58:00 subfolder2
-   rw-r--r-- 1   ftp    ftp    1KB    2012-06-15 12:49:00 textitem.txt


   Parent: ftp://ftp.contoso.com/folder/subfolder1

Dir Right     Ln  User   Group  Size   ModifiedDate        Name
--- -----     --  ----   -----  ----   ------------        ----
d   rwxr-xr-x 2   ftp    ftp           2012-06-19 12:58:00 subfolder11
-   rw-r--r-- 1   ftp    ftp    21KB   2012-06-19 09:20:00 test.xlsx
-   rw-r--r-- 1   ftp    ftp    14KB   2012-06-19 11:27:00 ziped.zip


   Parent: ftp://ftp.contoso.com/folder/subfolder1/subfolder11

Dir Right     Ln  User   Group  Size   ModifiedDate        Name
--- -----     --  ----   -----  ----   ------------        ----
-   rw-r--r-- 1   ftp    ftp    14KB   2012-06-19 11:27:00 ziped.zip


   Parent: ftp://ftp.contoso.com/folder/subfolder2

Dir Right     Ln  User   Group  Size   ModifiedDate        Name
--- -----     --  ----   -----  ----   ------------        ----
-   rw-r--r-- 1   ftp    ftp    1KB    2012-06-15 12:49:00 textitem.txt
-   rw-r--r-- 1   ftp    ftp    14KB   2012-06-19 11:27:00 ziped.zip





-------------------------- EXAMPLE 4 --------------------------

PS P:\&gt;$ftpFile = Get-FTPChildItem -path /folder/subfolder1/test.xlsx


PS P:\&gt; $ftpFile | Select-Object Parent, Name, ModifiedDate

Parent                                  Name
ModifiedDate
------                                  ----
------------
ftp://ftp.contoso.com/folder/subfolder1 test.xlsx
2012-06-19 09:20:00

RELATED LINKS
Set-FTPConnection

Just been testing against a home ftp server and Get-FTPChildItem seems to iterate through files in a given directory, but as only one file appears in the local directory (regardless of the fact that there is six in the FTPP location). So it seems to be copting one file, timestamping and appending 001, then getting the next file and overwriting the last one on the local directory before again appending 001 (or which sequence number the $StartNum variable is the associated with at that point)

VERBOSE: Performing the operation “Download item: ‘ftp://192.168.0.18/NatWest/l6xq1 - Copy (2).txt’” on target “”.
226 Transfer complete.

VERBOSE: Performing the operation “Download item: ‘ftp://192.168.0.18/NatWest/l6xq1 - Copy (2).txt’” on target “C:/Cred/L6XQ0201.004.txt”.
226 Transfer complete.

VERBOSE: Performing the operation “Download item: ‘ftp://192.168.0.18/NatWest/l6xq1 - Copy (3).txt’” on target “C:/Cred/L6XQ0201.004.txt”.
226 Transfer complete.

VERBOSE: Performing the operation “Download item: ‘ftp://192.168.0.18/NatWest/l6xq1 - Copy (4).txt’” on target “C:/Cred/L6XQ0201.004.txt”.
226 Transfer complete.

VERBOSE: Performing the operation “Download item: ‘ftp://192.168.0.18/NatWest/l6xq1 - Copy (5).txt’” on target “C:/Cred/L6XQ0201.004.txt”.
226 Transfer complete.

VERBOSE: Performing the operation “Download item: ‘ftp://192.168.0.18/NatWest/l6xq1 - Copy (6).txt’” on target “C:/Cred/L6XQ0201.004.txt”.
226 Transfer complete.

VERBOSE: Performing the operation “Download item: ‘ftp://192.168.0.18/NatWest/l6xq1 - Copy.txt’” on target “C:/Cred/L6XQ0201.004.txt”.

Get-FTPItem has an -Overwrite parameter which has a default setting of $False, but changing this to $True doesn’t yield a different result.

Any ideas where I’m going wrong with this?

Also, the output of Get-FTPChildItem needs to be piped to the Get-FTPItem command, but ForEach doesn’t work this way (the pipe between the two commands wont be accepted.

ForEach-Object should work on Face value, but this stops the script retrieving any files at all

Get-FTPChildItem -Session $Session -Path $FTPPath -recurse | ForEach-Object {Get-FTPItem -session $session -verbose -localpath $LocalPath -overwrite:$Confirm -confirm:$false}