Giter Site home page Giter Site logo

winscp's Introduction

WinSCP PowerShell Module Wrapper

CI/CD

Use at your own risk.

This module can be installed from the PowerShellGet Gallery, You need WMF 5 to use this feature.

# Inspect
Save-Module -Name WinSCP -Path <Path>

# Install
Install-Module -Name WinSCP

WinSCP Cmdlets

Example

# Capture credentials.
$credential = Get-Credential

# Set the options to open the WinSCPSession with
$sessionOption = New-WinSCPSessionOption -HostName ftp.tomohulk.github.io -Protocol Ftp -Credential $credential

# Open the session using the SessionOptions object.
# New-WinSCPSession sets the PSDefaultParameterValue of the WinSCPSession parameter for all other cmdlets to this WinSCP.Session object.
# You can set it to a variable if you would like, but it is only necessary if you will have more then one session open at a time.
New-WinSCPSession -SessionOption $sessionOption

# Use that session to create a new Directory.
New-WinSCPItem -Path './remoteDirectory' -ItemType Directory

# Upload a file to the directory.
Send-WinSCPItem -Path 'C:\localDirectory\localFile.txt' -Destination '/remoteDirectory/'

# Close and remove the session object.
Remove-WinSCPSession

Check back regularly for updates.

This project is licensed with GNU GENERAL PUBLIC LICENSE.

winscp's People

Contributors

andrewdp23 avatar chrgraefe avatar dotps1 avatar hvveen avatar jeffreymcclain avatar tomohulk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

winscp's Issues

Error "$LocalPath must be a directory."

So I'm getting an error when I attempt a Sync-WinSCPPath command.

PS> Sync-WinSCPPath -RemotePath '\home\user\folder\' -LocalPath 'C:\some\folder\here\ -Mode Remote 
Sync-WinSCPPath : C:\some\folder\here\ must be a directory.
At line:10 char:1
+ Sync-WinSCPPath -RemotePath '\home\user\folder\' -LocalPath 'C:\some\folder\here\' 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Sync-WinSCPPath

At first I thought maybe I specified the folder wrong or I terminated with a slash and it needs it without, but that's not it. So I set a breakpoint on line 73 of Sync-WinSCPPath.ps1 which is the Write-Error command from this bit of code

} else {
            $LocalPath = Get-Item -Path $LocalPath

            if (-not ($LocalPath.PSIsContainer)){
                Write-Error -Message "$LocalPath must be a directory."

                continue
            }

In the debugger

[DBG]: PS C:\>> $LocalPath.GetType();

IsPublic IsSerial Name                                     BaseType                                                                        
-------- -------- ----                                     --------                                                                        
True     True     String                                   System.Object    

Huh? How? In a normal powershell window:

PS> $p = 'C:\some\folder\here\'

PS> $p = Get-Item -Path $p

PS> $p.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                    
-------- -------- ----                                     --------                                                                                                                    
True     True     DirectoryInfo                            System.IO.FileSystemInfo  

I don't understand how that variable could possibly have turned into a string. I mean you're reusing that variable with get-item, but I don't see an issue with that. It's almost as if that line of code with Get-Item isn't being ran but I know it is because I toggled a break point there and stepped into it as well and afterwards it's still a string! I'm stumped.

more examples

Request for more help examples for each command.

For example, for Sync-WinSCPPath, it's not very clear what the Mode options accomplish exactly (local, remote, both), unless you test them on your own.

receive-winscpitem

receive-winscpitem needs to return an object even if the download attempt fails. right now it doesn't, so i have to resort to creating a whole custom object based off the -errorvariable result.

Wildcard file retrieval

Moving from TechNet: https://gallery.technet.microsoft.com/WinSCP-PowerShell-Module-ee1601ff/view/Discussions

Written Fri 2:39 PM

Jonathan Otto
How can we retrieve a specific file type using a wildcard file name?

Receive-WinSCPItem -WinSCPSession $session -Path "./remote/path/*.xml" -Destination C:\Download

Receive-WinSCPItem : Cannot find path: ./remote/path/*.xml/ because it does not exist.

At line:1 char:1

  • Receive-WinSCPItem -WinSCPSession $session -Path "./remote/path/*.xml" -Destinat ...
  • - CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    - FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Receive-WinSCPItem
    
    

From the parameter info, which doesn't seem to work properly...

.PARAMETER Path
Full path to remote directory followed by slash and wildcard to select files or subdirectories to download. When wildcard is omitted (path ends with slash), all files and subdirectories in the remote directory are downloaded.

Written Fri 2:44 PM

dotps1
I think its an issue with the function allity,

can you open the following file:
\Functions\Receive-WinSCPItem.ps1

then delete lines 45-49. save the module, reimport it, and try again.

basically, it is testing for /remote/path/*.xml which doesn't exists because of the *. please let me know the outcome. thank you.

Written Fri 4:41 PM

Jonathan Otto
The error is no longer in PowerShell, but the transfer still fails. From the session log:

2015-09-25 16:34:29.712 Script: get -nopermissions -preservetime -transfer="binary" -- "./remote/path/.xml/" "C:\Download"
. 2015-09-25 16:34:29.712 Listing directory "/remote/path/
.xml".
2015-09-25 16:34:29.712 Type: SSH_FXP_OPENDIR, Size: 27, Number: 523
< 2015-09-25 16:34:29.761 Type: SSH_FXP_STATUS, Size: 33, Number: 523
< 2015-09-25 16:34:29.761 Status code: 2, Message: 523, Server: File not found, Language: en
. 2015-09-25 16:34:29.761 Asking user:
. 2015-09-25 16:34:29.761 Error listing directory './remote/path/.xml'. ("No such file or directory.
. 2015-09-25 16:34:29.761 Error code: 2
. 2015-09-25 16:34:29.761 Error message from server (en): File not found")
< 2015-09-25 16:34:29.761 Script: Error listing directory './remote/path/
.xml'.
< 2015-09-25 16:34:29.761 Script: No such file or directory.
< 2015-09-25 16:34:29.762 Error code: 2
< 2015-09-25 16:34:29.762 Error message from server (en): File not found
. 2015-09-25 16:34:29.762 Script: Failed

I was able to work around it using a combination of another function. I'm definitely curious if there is a better way to do accomplish this kind of wildcard download, but this method appears to work.

$RemoteXmlFile = Get-WinSCPChildItem -WinSCPSession $session -Path '/remote/path/' -Filter *.xml
$LocalPath = "C:\Download"
ForEach ($file in $RemoteXmlFile) {Receive-WinSCPItem -WinSCPSession $session -Path $file -Destination $LocalPath}

Typo (?) - GiveUpSecureityAndAcceptAnyTlsHostCertificate

Noticed this long-standing naming discrepancy between WinSCP SessionOptions variable name and WinSCPWrapper parameter for New-WinSCPSession:

  • WinSCP: GiveUpSecurityAndAcceptAnyTlsHostCertificate
  • WinSCPWrapper: GiveUpSecureityAndAcceptAnyTlsHostCertificate

This seems to represent a bug:

  • The New-WinSCPSession loop which assigns WinSCP.SessionOptions values seems to fail to identify GiveUpSecureityAndAcceptAnyTlsHostCertificate as a valid member of that object.
  • As a consequence, upon attempting to open the session, I received this error, "New-WinSCPSession : Exception calling "Open" with "1" argument(s): "Connection failed. Peer certificate rejected Disconnected from server Connection failed.""

When I correct the parameter name, it seems New-WinSCPSession correctly identifies the WinSCP.SessionOptions member, from the bound parameter, and my connection succeeds.

Thank you,

Kevin

Links:
https://winscp.net/eng/docs/library_sessionoptions
https://github.com/dotps1/WinSCP/blame/master/WinSCP/Public/New-WinSCPSession.ps1#L34

Send-WinSCPItem -Remove Switch

The Send-WinSCPItem -Remove switch will remove not only the source file, but the folder that it is contained in.

Example:

$filetransfer = Send-WinSCPItem -Path $transferitems -Destination $site.destPath -Remove

This is moving a file from a location on the local E:\ drive to the /testing folder on the SFTP site then deleting only the file after. However as mentioned, it deletes the folder it's contained in too.

$transferitems looks like this: $transferitems = Get-Item -Path $site.sourcePath

DLL handling

Since this is a module why not add the dll handling as part of the module? This would allow for strong typing of the variables in each cmdlet, instead of using parameter validation to ensure the proper values are being submitted.

Help

The Help
<#
SYNOPSIS ...

should bi directly after the
function Name {
not in front of it
;-)

dot sourcing SshPrivateKeyPath causing error.

When dot sourcing the SshPrivateKeyPath in the New-WinSCPSession cmdlet causes the the connection to fail because the string is not being resolved to the path of the certificate. This results in the following error:

New-WinSCPSession : Exception calling "Open" with "1" argument(s): "Disconnected: No supported authentication methods available (server sent: publickey)"

Receive-WinSCPItem / Send-WinSCPItem -Remove

There doesn't seem to be a way to use the -Remove tag without deleting the folder. Optimally we would be able to remove just the downloaded files, leaving the folder intact.

Issue with file checksum

In Get-WinSCPItemChecksum

"ValueFromPipelineByProperyName" should be "ValueFromPipelineByPropertyName"

[Parameter(Mandatory = $true,
ValueFromPipelineByPropertyName = $true)]
[ValidateScript({ -not ([String]::IsNullOrWhiteSpace($_)) })]
[String[]]
$Path

New-WinSCPItem fails when creating Directories

New-WinSCPSession is failing when creating directories.

creating files works:

PS C:\> New-WinSCPItem -Name 'Test.txt'


   Directory: /

FileType             LastWriteTime     Length Name                                                                                                                                                                                                                                        
--------             -------------     ------ ----                                                                                                                                                                                                                                        
-           12/11/2015 10:32:26 AM          0 Test.txt

creating directories fail:

PS C:\> New-WinSCPItem -Name 'Test' -ItemType Directory
New-WinSCPItem : Cannot bind argument to parameter 'Path' because it is null.
At line:1 char:1
+ New-WinSCPItem -Name 'Test' -ItemType Directory
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,New-WinSCPItem

Session variable disposed after latest commits?

Hi, I am getting an "object is disposed" error for my session variable using the latest build. I am following this example from the documentation:

PS C:\> $session = New-WinSCPSessionOptions -Hostname myftphost.org -Username ftpuser -password "FtpUserPword" -SshHostKeyFingerprint "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" | Open-WinSCPSession
PS C:\> Get-WinSCPDirectoryContents -WinSCPSession $session -Path "rDir/" -ShowDetails

I reverted to the 25-Jan-2015 build and the error disappears. Can you duplicate this issue?

New-WinSCPTransferOptions -ResumeSupport

Hi there,

I noticed that the function didn't support resume support.
The script I have built needs it off, so have extended your function to support it.

I am new to Git hub so wasn't sure how I could contribute so please find below the working function with ResumeSupport included.

<#
.SYNOPSIS
    Sets options for file transfers.
.DESCRIPTION
    Sets available options for file transfers between the client and server.
.INPUTS
    None.
.OUTPUTS
    WinSCP.TransferOptions.
.PARAMETER FileMask
    http://winscp.net/eng/docs/file_mask
.PARAMETER FilePermissions
    Permissions to applied to a remote file (used for uploads only).
.PARAMETER PreserveTimeStamp
    Preserve timestamp (set last write time of destination file to that of source file). Defaults to true.
.PARAMETER TransferMode
    Possible values are TransferMode.Binary (default), TransferMode.Ascii and TransferMode.Automatic (based on file extension).
.EXAMPLE
    PS C:\> New-WinSCPTransferOptions -PreserveTimeStamp -TransferMode Binary

    PreserveTimestamp : True
    FilePermissions   : 
    TransferMode      : Binary
    FileMask          : 
    ResumeSupport     : default
.EXAMPLE
    PS C:\> New-WinSCPTransferOptions -FilePermissions (New-WinSCPFilePermissions -GroupExecute -OtherRead)

    PreserveTimestamp : True
    FilePermissions   : -----xr--
    TransferMode      : Binary
    FileMask          : 
    ResumeSupport     : default
.NOTES
.LINK
    http://dotps1.github.io/WinSCP
.LINK
    http://winscp.net/eng/docs/library_transferoptions
#>
Function New-WinSCPTransferOptions
{
    [CmdletBinding()]
    [OutputType([WinSCP.TransferOptions])]

    Param
    (
        [Parameter()]
        [ValidateScript({ -not ([String]::IsNullOrWhiteSpace($_)) })]
        [String]
        $FileMask,

        [Parameter()]
        [WinSCP.FilePermissions]
        $FilePermissions,

        [Parameter()]
        [Switch]
        $PreserveTimeStamp,

        [Parameter()]
        [WinSCP.TransferMode]
        $TransferMode,

        [Parameter()]
        [WinSCP.TransferResumeSupportState]
        $ResumeSupport
    )

    Begin
    {
        $transferOptions = New-Object -TypeName WinSCP.TransferOptions


        foreach ($key in $PSBoundParameters.Keys)
        {
            try
            {
                if($key -eq 'ResumeSupport'){
                    $transferOptions.ResumeSupport.State = $PSBoundParameters.$($key)
                }else{
                    $transferOptions.$($key) = $PSBoundParameters.$($key)
                }
            }
            catch [System.Exception]
            {
                throw $_
            }
        }
    }

    End
    {
        return $transferOptions
    }
}

Open Session Handling

Another session handling option could be to accept a session object, opened or closed, and manage the session internally. if the session was opened when it was passed you should leave it opened, otherwise it should be closed. The WinSCP wiki PowerShell examples only take an object, and explicitly open and close the session around the action taken.

Using -Path with as a type [String[]] does not work.

Example throws error:

$s = New-WinSCPSession -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:USERNAME, (New-Object -TypeName System.Security.SecureString)) -HostName $env:COMPUTERNAME -Protocol Ftp

Move-WinSCPItem -WinSCPSession $s -Path '/File1.txt', '/File2.txt' -Destination '/SubFolder'

throws error due to helper function for formatting the Path strings.

Unable to verify CheckSum

Hi,

When trying to verify the checksum, I always have this error :

Get-WinSCPItemChecksum : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

Here is the command used :

New-WinSCPSession -Credential $credentials -Hostname $hostname -Protocol Sftp -GiveUpSecurityAndAcceptAnySshHostKey | Get-WinSCPItemChecksum -Algorithm 'sha-1' -Path $path

Same results with :

Get-WinSCPItemChecksum -WinSCPSession $session -Path $path -Algorithm 'sha-1'

Have you any idea ?

Thanks.

ValueFromPipelineByPropertyName = true

Hi,

Could you please add this to more named parameters? The obvious examples are hostname/port/protocol of New-WinSCPSession. I see you already have it on $SshHostKeyFingerprint.

I tend to pull these parameters from a database. Being able to Pipe these parameters by splatting them using a hash table or custom object would be sweet.

Great job on this btw. Been using in production for a while.

Confirmation in Remove-WinSCPItem

Currently Remove-WinSCPItem asks for manual confirmation on all deletes.
This is not really useful in a scripting context :)
Is it possible to add a -force to change this behavior to delete without confirmation?

new-winscpitem does not create folder and errors out

I try to create a directory if it does not exist:
if (-not (Test-WinSCPPath -WinSCPSession $session -Path $HistoryPath))
{
New-WinSCPItem -WinSCPSession $session -Path $name -ItemType Directory
}

The folder does not get created and I get this error:

Get-WinSCPItem : Cannot find path: ./VanBreda/ because it does not exist.
At C:\Program Files\WindowsPowerShell\Modules\WinSCP\Functions\New-WinSCPItem.ps1:90 char:17

  •             Get-WinSCPItem -WinSCPSession $WinSCPSession -Path $p
    
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
    • FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-WinSCPItem

The term 'New-WinSCPSessionOptions' is not recognized as the name of a cmdlet

Hi,

I've downloaded an installed your plugin through the Install-Module cmdlet.

When I'm trying to run the code in your Example 1, with my server, user and password of course, I get a Powershell error:

New-WinSCPSessionOptions : The term 'New-WinSCPSessionOptions' is not recognized as the name of a cmdlet, function, script 

file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.

Any ideas on what I might have configured incorrectly on my side, or is there a know problem that causes this error?

New Function: New-WinSCPSessionOption

Split out the WinSCP.SessionOptions properties into a separate function. Doing this for two reasons.

  1. This makes more sense, it will emulate functionallity similar to New-CimSession -SessionOption (New-CimSessionOption).
  2. A standalone WinSCP.SessionOptions object is needed to implement the ScanFingerprint method [WinSCP.Session].ScanFingerprint([WinSCP.SessionOptions]).

Remove file check in Send/Receive-WinSCPItem

The file check needs to be removed from the Send/Receive-WinSCPItem as it prevents the use of the following code:

Receive-WinSCPItem -WinSCPSession [WinSCP.Session] -Path '/RemoteFolder/*.txt' -Destination 'C:\Downloads'

The test for /RemoteFolder/*.txt fails, as there is no file with that name, and prevents the transfer of files by wildcard.

New:WinSCPSession: bug in $SshPrivateKeyPassphrase parameter

I found out a bug in the management of the parameter $SshPrivateKeyPassphrase

The parameter has been defined as SecureString, see below:

    [Parameter()]
    [ValidateScript({ -not ([String]::IsNullOrWhiteSpace($_)) })]
    [SecureString]
    $SshPrivateKeyPassphrase = $null,

But insider the function code you try to assign to a string (the decoded string) into the same parameter:

$SshPrivateKeyPassphrase = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SshPrivateKeyPassphrase))

This raises to the following error:

Cannot convert the "*******" value of type "System.String" to type "System.Security.SecureString".

Thank you
Martino

Using Receive-WinSCPItem with -Remove Param on Directory thows exception

After establishing a valid Session, using:

$so = New-WinSCPSessionOptions -HostName host -UserName user -Password word -Protocol Ftp
$s = Open-WinSCPSession -SessionOptions $so
Receive-WinSCPSession -WinSCPSession $s -RemotePath "./Folder" -LocalPath "C:\Folder" -Remove

Throws an exception:

Exception calling "GetFiles" with "3" argument(s): "Operation is not valid due to the current state of the object." 

I have opened an issue on WinSCPs site:
http://winscp.net/forum/viewtopic.php?p=55303#55303

Typo in function Remove-WinSCPItem

Hi,

I've run into a small bug: When calling function Remove-WinSCPItem from a script I get the following error -

Property 'ValueFromPipelingByPropertyName' cannot be found for type 'System.Management.Automation.ParameterAttribute'.
At C:\Program Files\WindowsPowerShell\Modules\WinSCP\5.7.4.3\Functions\Remove-WinSCPItem.ps1:49 char:9
+         [Parameter(Mandatory = $true,
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundForType

The parameter attribute appears to be a typo in the function - ValueFromPipelingByPropertyName rather than ValueFromPipeline. I could fix this myself but I am new to Github and don't quite know how to contribute my own bugfix or if it is appropriate to do so. Thanks!

Cannot install 5.7.6 on 2012 R2 with WMF 5.0 Preview

I was trying to install 5.7.6 on my home server and found that no matter what I tried, it would not install.
5.7.4 installed however, but upgrades or clean installs did not work.
Oddly, on my Windows 10 system, it installed with no issues.
Here's a copy of the powershell log (cleaned up) from my server.
winscplog.txt
Here's a screenshot of the error in powershell:
winscpscreenie

Please let me know if you need anything from me, I'll be happy to provide it :)

Issue with Send-WinSCPItem

Hi I just tried you WinSCP for PowerShell and want to report an issue.
I've been trying to get file uploads working and used the following

$Session = New-WinSCPSession -Credential $FTPCredentials -HostName $FTPServer -Protocol Sftp -GiveUpSecurityAndAcceptAnySshHostKey

$TransferOptions = New-WinSCPTransferOption -PreserveTimestamp $True -TransferMode Binary

$Send = Send-WinSCPItem -WinSCPSession $Session -Path 'E:\Folder\file_name.txt' -Destination '/Home/CSV/file_name.txt' -TransferOptions $TransferOptions

$Send | FL

I get this as an output

Transfers : {E:\Folder\file_name.txt}
Failures : {WinSCP.SessionRemoteException: Cannot create remote file '/Home/CSV/Home/CSV/file_name.txt/file_name.txt.filepart'. --->
WinSCP.SessionRemoteException: General failure (server should provide error description).
Error code: 4
Error message from server: failed to open file
--- End of inner exception stack trace ---}
IsSuccess : False

I editited the Send-WinSCPItem.ps1 and changed
$WinSCPSession.PutFiles($item, (Format-WinSCPPathString -Path $($Destination)), $Remove.IsPresent, $TransferOptions)

To this

$WinSCPSession.PutFiles($item, $Destination, $Remove.IsPresent, $TransferOptions)

It looks the Format-WinSCPPathString function is messing up the string.

Refactoring sessionValueFromPipeLine

Very low priority; please feel free to disregard

Time/motivation permitting, would you please consider refactoring variable "sessionValueFromPipeLine"? Namely, the following expression seems to return "True" not for pipeline values, but for other situations:
$sessionValueFromPipeLine = $PSBoundParameters.ContainsKey('WinSCPSession')

This seems counterintuitive to me, as this expression seems to assign variable sessionValueFromPipeLine the value False, when WinSCPSession is provided on the pipeline. This gets handled in the End block, as "if (-not ($sessionValueFromPipeLine)) {...", per auto-disposal when input provided on the pipeline.

In summary, it seems to work, but the variable seems worded in a confusing way (to me). Maybe refactor it to something like "$sessionValueAutoRemove" = (-not $PSBoundParameters.ContainsKey('WinSCPSession'))"; (?)

What do you think (?)

The following example lists a few situations which return true:

$Global:PSDefaultParameterValues.Remove("Test:Name")

Function Test {
  [CmdletBinding()]
  param(
  [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName, ValueFromPipeline)]
  [string] $Name
  )
  begin { 
    $boundSessionValue = $PSBoundParameters.ContainsKey('Name')

  }
  process
  {
    "boundNameValue = $($boundSessionValue); " + "Name = " + $Name
  }
  end { 
  }

} # End Test

$NewLine = "`r`n"

# boundNameValue = True; Name = Fred
"Test -Name ""Fred""--explicitly bound parameter"
Test -Name "Fred"

# boundNameValue = True; Name = Fred
$NewLine + `
"Test ""Fred""--implicitly bound parameter"
Test "Fred"

# boundNameValue = False; Name = Fred
$NewLine + `
"""Fred"" | Test--implicitly bound pipeline parameter"
"Fred" | Test

$NewLine + `
"Setting `$Global:PSDefaultParameterValues"
$Global:PSDefaultParameterValues.Add("Test:Name", "Bob")

# boundNameValue = True; Name = Fred
$NewLine + `
"Test -Name ""Fred""--explicitly bound parameter"
Test -Name "Fred"

# boundNameValue = True; Name = Fred
$NewLine + `
"Test ""Fred""--implicitly bound parameter"
Test "Fred"

# boundNameValue = True; Name = Bob
$NewLine + `
"Test--no passed parameter, uses Global:PSDefaultParameterValues"
Test

# Error: overriding default with pipeline not allowed
#"""Fred"" | Test--override default with pipeline parameter"
#"Fred" | Test

Source files (search query follows):

  1. WinSCP/Public/Invoke-WinSCPCommand.ps1
  2. WinSCP/Public/Test-WinSCPPath.ps1
  3. WinSCP/Public/Get-WinSCPItem.ps1
  4. WinSCP/Public/Get-WinSCPItemChecksum.ps1
  5. WinSCP/Public/Remove-WinSCPItem.ps1
  6. WinSCP/Public/Move-WinSCPItem.ps1
  7. WinSCP/Public/Receive-WinSCPItem.ps1
  8. WinSCP/Public/Send-WinSCPItem.ps1
  9. WinSCP/Public/Sync-WinSCPPath.ps1
  10. WinSCP/Public/Rename-WinSCPItem.ps1
  11. WinSCP/Public/Get-WinSCPChildItem.ps1
  12. WinSCP/Public/New-WinSCPItem.ps1

Source file search query:
https://github.com/dotps1/WinSCP/search?q=sessionValueFromPipeLine&type=Code&utf8=%E2%9C%93

Again, very low priority. Please do what you prefer. If you're in the file to change something anyway, it might represent something to cleanup--it might help clarify this better for someone like me, in the future. : )

Thank you,

Kevin

Get-WinSCPChild Item Filtering

The basic filtering on the Get-WinSCPChildItem filtering is great, but it would be even better if it could accept multiple filters the same way as PowerShell's built in Get-ChildItem cmdlet does.

Thank you.

Sync to full destination path

I'm trying to sync to a customer's server and by default it sets the sftp session's working directory to the account's home directory, but I need to sync the files to /D/Sites/wwwroot.

When I use "/D/Sites/wwwroot" as the destination parameter it appends a dot to the beginning of the path (via the Format-WinSCPPathString cmd) making it a relative path, and so the sync errors:
Sync-WinSCPPath : Cannot find path: ./D/Sites/wwwroot because it does not exist.

Is there anyway to use a full path as the destination, not a relative one?

Thanks
Dan

Issue with Receive-WinSCPItem

With the recent updates, you have changed the way Receive-Winscpitem works:
Before, it was possible to set "destination" to a filename different from path, and the file would be renamed locally to that filename.

For example, if I have a Path of "./filename.txt" and a Destination of "c:\tmp\temporary.txt", the file would be renamed locally to "temporary.txt".

Now there is this check:
if ((Get-Item -Path $Destination).Attributes -eq 'Directory' -and -not $Destination.EndsWith(''))
{
$Destination += ''
}

It I specify a local filename as $destination tries to do a "get-item" of a not-yet existing path, and throws an error.

Could it be possible to revert to the previous behavior?

Non-terminating errors not powershell standard

Hi again,

I am finished with my project but I just wanted to let you know of one more bug/enhancement request.

I use $ErrorActionPreference and the -ErrorAction property fairly regularly but your try/catch around WINSCP methods is not working properly. This method of error trapping will not throw if the file transfer is unsuccessful.

try{
    $WinSCPSession.GetFiles('/fakepath/','C:\TEMP',$false, (New-Object -TypeName WinSCP.TransferOptions)) 
}
catch {
    Write-Error 'This should error but does not.'
}

What has been necessary for me whenever sending or receiving files using your module is to add the following code.

$GetResults = Receive-WinSCPItem -WinSCPSession $WinSCPSession -Path '/fakepath/' -Destination 'C:\TEMP'
IF ($GetResults.IsSuccess -ne $true) {Write-Error $GetResults.Failures}

It would be great if you would add something like this to the relevant methods so that native powershell error handling started working.

Test-WinSCPPath fails on '/'

The following commands will fail. It is testing the homepath as a file and fails, which breaks Get-WinSCPChilditem

Test-WinSCPPath -WinSCPSession $Session -Path '/'

$WinSCPSession.FileExists('/')

These commands work.

$ftp.ListDirectory('/')

$WinSCPSession.ListDirectory('/').Files

Rename-WinSCPItem broken

User SMFX [email protected] sends the following message to the owners of item 'WinSCP'.
There is a problem in the Rename-WinSCPItem function. The $item.name references on line 53 & 54 should be $item.FullName to capture the path as well as the file name. I'm not sure if WinSCP changed the object in a previous version, but if you use any folders Rename-WinSCPItem will not work.
$newPath = "$($item.FullName.Substring(0, $item.FullName.LastIndexOf('/') + 1))$NewName" $WinSCPSession.MoveFile($item.FullName, $newPath)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.