简体   繁体   中英

Inserting variables as command options in Powershell scripts?

Newb here, powershell experience is a solid 1 hour but I can't seem to find the answer to this anywhere so I'm starting to think it may not be the problem. I am attempting to create a script to allow me to connect to my ubuntu machine. The ip address changes with each reboot, so I created a bash script that outputs the ip address into ip.txt and im sure that is working well (no extra spaces or undesired characters).

I have created a variable that gives me the string from the file, and although the script runs successfully, the connection doesnt work. if I execute the command and manually enter the ip, it works.

$myip=Get-content 'C:\Users\USER\Documents\ip.txt' -Raw

netsh interface portproxy add v4tov4 listenport=3390 listenaddress=0.0.0.0 connectport=3390 connectaddress=$myiptxt

edit: I do not get any errors

As suggested in the comment information, the IP Address in the ip.txt is probably preceded and/or succeeded by one or more new line (Cr/Lf) characters.

If you use the -Raw parameter, Get-content will return all the lines including newline characters as a single string ( [String ]). At the other hand, if you do not include the -Raw , Get-content will return all the lines as separate strings ( [String[]] ), which might cause an issue in your case as well.

To remove all possible white-space characters arround the IP Address, you might use the Trim() method which removes all leading and trailing white-space characters from the current string by default:

$myip=Get-content 'C:\Users\USER\Documents\ip.txt' -Raw
$myip = $myip.trim()
netsh interface portproxy add v4tov4 listenport=3390 listenaddress=0.0.0.0 connectport=3390 connectaddress=$myip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM