matthy
matthy

Reputation: 8334

Using PowerShell variable for example in FTP.exe

How do you use powershell variables when you run program in it? Is it simply not possible?

Example:

$url = "test.com"
ftp
ftp> open $url

Unknown host $url.

Upvotes: 1

Views: 953

Answers (1)

Duncan
Duncan

Reputation: 95652

The FTP command will read commands from a file, so you can use Powershell to create a file containing the required commands and then tell the command to read from the file. It is best to create a unique name for the temporary file and remember to delete it when you are finished:

PS C:\> $url = "test.com"
PS C:\> $filename = "foo.bar"
PS C:\> $tempFile = [io.path]::GetTempFileName()
PS C:\> @"
>> open $url
>> get $filename
>> quit
>> "@ >>$tempFile
>>
PS C:\> cat $tempFile
open test.com
get foo.bar
quit
PS C:\> ftp -s:$tempFile
PS C:\> remove-item $tempFile

A multi-line string @"..."@ is a good way to create a temporary file for external commands because it lets you write the commands in a natural way.

Other commands may not accept input from a file. In that case it is worth checking whether you can specify all of the needed commands on the command line. Many non-Powershell commands will actually accept multi-line arguments even though when run from cmd.exe there would be no way to pass such arguments. For example:

PS C:\python34> python -c @"
>> for i in range(10):
>>    print(i)
>> "@
>>
0
1
2
3
4
5
6
7
8
9
PS C:\python34>

Upvotes: 4

Related Questions