如何使用PSCP从服务器未知子目录复制指定文件至本地?
Great question! The catch here is that PSCP doesn’t have a built-in way to recursively search for files across subfolders directly. But we can pair it with a remote SSH command to locate the file first, then use that path to copy it over. Here’s how to do it step by step:
Step 1: Locate the file’s full path on the server
First, we’ll use the find command (standard on most Linux/Unix servers) via SSH to find where FileName.txt lives under /temp:
ssh -pw Password User@Machinenumber "find /temp -name 'FileName.txt' -type f"
-name 'FileName.txt': Targets the exact filename we’re looking for-type f: Ensures we only match files (not folders with the same name)- This command will output the full path to the file (e.g.,
/temp/Subfolder2/FileName.txt) if it exists.
Step 2: Copy the file using the found path
Once we have the path, we can pass it to PSCP. The method varies slightly depending on whether you’re using Windows Command Prompt (CMD) or PowerShell:
For Windows CMD
Use a for loop to capture the output of the SSH command and feed it to PSCP:
for /f "delims=" %%i in ('ssh -pw Password User@Machinenumber "find /temp -name 'FileName.txt' -type f"') do pscp.exe -pw Password User@Machinenumber:"%%i" C:\Users\Desktop
The delims= part ensures we capture the full path even if it contains spaces (though your example paths don’t have them, it’s a safe practice).
For PowerShell
It’s a bit cleaner—we can store the path in a variable first, then use it in PSCP:
$filePath = ssh -pw Password User@Machinenumber "find /temp -name 'FileName.txt' -type f" pscp.exe -pw Password User@Machinenumber:"$filePath" C:\Users\Desktop
Important Notes
- Multiple matching files: If there are multiple
FileName.txtfiles in different subfolders, this will copy all of them to your desktop (later files will overwrite earlier ones). To avoid this, add-maxdepth 2to thefindcommand to only search one level deep under/temp:find /temp -maxdepth 2 -name 'FileName.txt' -type f - Security warning: Putting your password in plaintext in commands is risky. For a safer approach, set up SSH key authentication—this lets you skip entering passwords entirely and avoids exposing your credentials.
- Server requirements: Make sure the remote server has the
findutility installed (most standard Linux/Unix distributions do).
内容的提问来源于stack exchange,提问作者siddhartha

