0

我正在准备一个 ps1 文件。它会静默安装一些程序。但是我的程序的设置文件保存在我的 USB 闪存驱动器中。在我的 ps1 文件中,

cd E:\User\User_Setups

此路径是我的 USB 闪存驱动器的路径。但它会在另一台机器上改变。也许是 G:\、F:\ 等。当然,我不想为每台不同的机器更改这条路径。PowerShell 如何通过命令行找到我的 USB 闪存驱动器的路径?

4

5 回答 5

3

我在我的 U 盘中添加了一个 VolumeLabel("MyToolBox") 并将以下行放在 profile.ps1 中:

Get-DriveInfo | % { if( $_.VolumeLabel -eq "MyToolBox"){ Set-Location $_.Name; ./Startup.ps1}}

Get-DriveInfo 来自 Pscx 模块:http://pscx.codeplex.com/ 也需要在您的配置文件中导入它...

Startup.ps1 脚本位于我的 U 盘的根目录中,并在 U 盘上注册别名以在会话中使用...

于 2012-03-14T14:58:30.783 回答
1

我已经用 WMI 做到了这一点:使用设备类型来获取驱动器号。以简化形式(真实脚本具有日志记录和错误处理)。我最初$deviceCaptionWin32_PnpEntity设备管理器获得:

    $objs = @(Get-WmiObject -Query "select Caption,__RELPATH from Win32_PnpEntity where caption=""$deviceCaption""")
    if ($objs.Length -eq 0) {
        throw "MP3 Player is not connected"
    } elseif ($objs.Length -gt 1) {
        throw "Seem to be multiple MP3 players connected"
    }
    $relPath = $objs[0];

    $objs = @(Get-WmiObject -Query "ASSOCIATORS OF {$relPath} where resultclass=Win32_DiskDrive")
    $relPath = $objs[0].__RelPath;

    $objs = @(Get-WmiObject -Query "ASSOCIATORS OF {$relPath} where resultclass=Win32_DiskPartition")
    $relPath = $objs[0].__RelPath;
    $objs = @(Get-WmiObject -Query "ASSOCIATORS OF {$relPath} where resultclass=Win32_LogicalDisk")
    $relPath = $objs[0].__RelPath;
    Write-Debug "RelPath #4: $($objs[0].__RelPath), drive: $($objs[0].DeviceID)"

    $objs[0].DeviceID

最后的表达式返回驱动器名称,类似于:(Q:它确实包含冒号)。

请注意,这假设设备有一个带有单个分区的磁盘。

于 2012-03-14T15:10:45.623 回答
0

可能有几种好方法可以做到这一点。就个人而言,我会在驱动器上放置一个 id 文件 disk.id 并以编程方式搜索每个驱动器,直到找到具有我正在寻找的 id 的 id 文件。像这样的东西:

#Start i at 65 to represent A
i=65
do {
  $idFile = Get-Content [char]$i:\disk.id -totalcount 1
  if( $idFile -eq "MyIdDrive" ) { #whatever your first line in the id file may be
       Write-Host "[char]$i is my drive!"
  }
  $i++
}
while ($i -le 65+26)

这是一种蛮力方法,您可能需要错误处理 Get-Content,但它应该适用于大多数 Windows 安装。您遇到问题的唯一情况是使用双写驱动器名称,然后您只需要创建一个更复杂的循环。

于 2012-03-14T15:11:55.733 回答
0

如果 Powershell 比常规 Windows CMD.exe 更强大,那为什么我只需要使用命令

ECHO %~dp0

在 CMD.exe 中回答您的问题?在我看来,您必须编写很多额外的代码来获取批处理或 cmd 文件信息的相对路径,这经常出现在批处理脚本中。Powershell 失败。

http://ss64.com/nt/syntax-args.html了解更多信息。

于 2013-09-23T21:22:11.847 回答
0

您可以获取当前文件,并使用它来获取当前的 USB 驱动器。

$currentDirectory = $myInvocation.MyCommand.ScriptBlock.File | Split-Path | Get-Item
$currentDirectory.PSDrive.Root
于 2013-09-23T22:06:00.417 回答