# If any command fails unexpectedly, we want the script to stop $ErrorActionPreference = "Stop" # Was it a complete upload? $endBy = $env:SSHUPLOADENDBY if ($endBy -ne "client") { # We can be sure an upload is complete only if the file was closed by the client # If the file was closed by the SSH Server because of a disconnect, $endBy will equal "cleanup" # If the upload was incomplete, this script performs a normal exit and does nothing # The client might reconnect and resume the upload exit } # Obtain the file name $filePath = $env:SSHUPLOADFILE if (-not $filePath) { Write-Error "Could not determine file name: environment variable SSHUPLOADFILE not set" } # If it's a virtual account, use the virtual account name # If it's not a virtual account, use the Windows account name $userName = $env:VIRTUSER if (-not $userName) { $userName = $env:SSHWINUSER if (-not $userName) { Write-Error "Could not determine user name: environment variables VIRTUSER or SSHWINUSER not set" } } # Use the current date # Alternative #1: could also use the file modification time set by the client # $file = Get-Item -LiteralPath $filePath # $destDate = $file.LastWriteTime # Alternative #2: If filename is in specific format, could also parse the date from filename $destDate = Get-Date $destDateStr = $destDate.ToString("yyyy-MM-dd") # Construct destination directory path # We're moving the file into a subdirectory of $destDirRoot. Example: C:\Incoming\Username\2022-03-17\ $destDirRoot = "C:\Incoming" $destDirUser = Join-Path $destDirRoot $userName $destDirPath = Join-Path $destDirUser $destDateStr # If the destination directory does not yet exist, create it if (-not (Test-Path -PathType Container -LiteralPath $destDirPath)) { # Assignment to variable avoids New-Item generating output $destDir = New-Item -ItemType Directory -Path $destDirPath } # Move the file # The filename is partially controlled by the client and might use unexpected characters # Use -LiteralPath instead of -Path to avoid insecure or unexpected behaviors Move-Item -LiteralPath $filePath -Destination $destDirPath