具有Powershell命令引号的批处理文件

乔治·斯托亚诺夫(Georgi Stoyanov)

我创建了一个脚本来更改IP地址/掩码和VLAN ID接口,但问题是要更改VLAN ID,我需要执行PowerShell命令。我的包含接口名称的变量包含一个空格,因此我需要将其用引号引起来。问题是我需要为同interfaceName一个插入两个变量,其中一个对Powershell命令使用单引号,而对于批处理netsh命令则使用单引号,否则,我将得到一个错误。这是我的批处理文件:

:: Configuration Variables
set ifName='Ethernet 2'
set connectionName="Ethernet 2"
set ipAddress=10.88.167.27
set subnetMask=255.255.255.240
set vlanID=100

:: set defaultGateway=x.x.x.x
:: set primaryDNS=x.x.x.x
:: set alternateDNS=x.x.x.x

:: Change of IP address and NetMask ::
netsh interface ipv4 set address name=%connectionName% source=static addr=%ipAddress% mask=%subnetMask%


:: Change VLAN ID ::
powershell -Command "& {Set-NetAdapter -Name %ifName% -VlanID %vlanID% -Confirm:$false}"
echo The VLAN ID of %ifName% has been successfully changed to %vlanID%

pause > null

我的批处理脚本运行良好,但是我只希望接口名称具有一个变量,而不是两个。我的问题是:

如果我ifName在change IP address命令中使用,则会收到以下错误:The filename, directory name, or volume label syntax is incorrect.

如果connectionName将PowerShell命令用于双引号,则会出现以下错误:

Set-NetAdapter : A positional parameter cannot be found that accepts argument '2'.
At line:1 char:4
+ & {Set-NetAdapter -Name Ethernet 2 -VlanID 100 -Confirm:$false}
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-NetAdapter], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Set-NetAdapter

我什至尝试将Powershell命令用单引号引起来并在内部使用,connectionName如下所示:

powershell -Command '& {Set-NetAdapter -Name %connectionName% -VlanID %vlanID% -Confirm:$false}'

但是网络接口VLAN保持不变。

约瑟夫·Z

使用set "varname=varvalue"语法模式设置变量,在必要时使用双引号将其引起echo "%varname%"然后,您的代码段应如下所示:

:: Configuration Variables
set "ifName=Ethernet 2"
set "connectionName=Ethernet 2"
set "ipAddress=10.88.167.27"
set "subnetMask=255.255.255.240"
set "vlanID=100"

:: Change of IP address and NetMask ::
netsh interface ipv4 set address name="%connectionName%" source=static addr=%ipAddress% mask=%subnetMask%

:: Change VLAN ID :: needs some tricky escaping

powershell -Command "& {Set-NetAdapter -Name """"'%connectionName%'"""" -VlanID %vlanID% -Confirm:$false}"
echo The VLAN ID of %ifName% has been successfully changed to %vlanID%

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章