首页 > 解决方案 > 从批处理文件运行 Powershell 命令以重命名网络驱动器

问题描述

我正在尝试创建一个批处理文件来重命名网络驱动器,因为“标签”不起作用。我创建了一个可以工作的 PS1 脚本,但我试图将脚本放入一个批处理文件中,这样我就可以运行处理几个连续的非 powershell 命令。我的PS1如下:

$ShellObject = New-Object –ComObject Shell.Application
$DriveMapping = $ShellObject.NameSpace('Z:')
$DriveMapping.Self.Name = 'DataStore'

我当前的批处理文件命令如下:

powershell -Command " $ShellObject = New-Object –ComObject Shell.Application; $DriveMapping = $ShellObject.NameSpace('Z:'); $DriveMapping.Self.Name = 'DataStore'"

这给了我以下错误:

Powershell CLI 错误

在此对象上找不到属性“名称”。验证该属性是否存在并且可以设置...

我关于如何解决这个问题的原始参考来自这里:如何在包含 & 符号的批处理文件中运行 powershell 命令。

当我无法让它工作时,我尝试了这里的格式:从 cmd 运行 powershell 命令

在这一点上,我尝试了几种不同的分号、引号、撇号等排列方式,但均未成功。这似乎是一个简单的问题,并感谢提供的任何帮助。

标签: powershellbatch-file

解决方案


$DriveMapping变量总是出现在这里$null

C:>type drivemap.bat
powershell -NoProfile -Command ^
    "$ShellObject = New-Object -ComObject Shell.Application;" ^
    "$DriveMapping = $ShellObject.NameSpace('Z:');" ^
    "$DriveMapping -eq $null;" ^
    "$DriveMapping.Self.Name = 'DataStore'"

因此,该Name物业不可用。

C:>powershell -NoProfile -Command     "$ShellObject = New-Object -ComObject Shell.Application;"     "$DriveMapping = $ShellObject.NameSpace('Z:');"     "$DriveMapping -eq $null;"     "$Drive
Mapping.Self.Name = 'DataStore'"
True
The property 'Name' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:128
+ ... 'Z:'); $DriveMapping -eq $null; $DriveMapping.Self.Name = 'DataStore'
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound

诸如此类的变量$DriveMapping不会在 PowerShell 调用中持续存在。再次运行 PowerShell 时,该$DriveMapping变量不存在。


推荐阅读