我正在尝试将字符串发送到Cisco路由器以进行配置
#Opens the port
$port= New-Object System.IO.Ports.SerialPort COM1,9600,None,8,one
$Hostname = "DuranDuran"
$port.WriteLine(("enable`nconfigure terminal`nHostname {0}`n") -f $Hostname)
$port.Close()
这项工作奇迹,它确实登录到服务器。但是,如果我想添加另一个字符串
$Hostname = "DuranDuran"
$interface = "FastEthernet 0"
$port.WriteLine(("enable`nconfigure terminal`nHostname {0}`ninterface {1}`n") -f $Hostname, $interface)
$port.Close()
执行此操作后,我收到此错误
Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list. At C:\Users\jorge.ramirez\Documents\SSHConfigRouter.ps1:10 char:81 + $port.WriteLine(("enable`nconfigure terminal`nHostname {0}`ninterface {1}`n") -f <<<< $Hostname,$interface) + CategoryInfo : InvalidOperation: (DuranDuran:String) [], RuntimeException + FullyQualifiedErrorId : FormatError
WriteLine
是否有问题?
答案 0 :(得分:0)
当您像这样致电WriteLine()
时:
$port.WriteLine("formatstring" -f $a, $b)
你实际上试图用2个参数("formatstring" -f $a
和$b
)而不是仅仅一个参数(插值字符串)来调用该方法。正如@PetSerAl已经指出的那样,有两种方法可以解决这个问题:
将参数放在括号中的格式运算符中,因此PowerShell不会将$b
视为WriteLine()
的单独参数:
$port.WriteLine("formatstring" -f ($a, $b))
将整个-f
语句放在括号中(即子表达式):
$port.WriteLine(("formatstring" -f $a, $b))