PowerShell-格式内的Var

时间:2018-10-30 11:59:09

标签: powershell

我真的是PowerShell的新手。我正在尝试制作一个脚本,以检测新连接的USB驱动器,并使用新名称和NTFS文件系统对其进行格式化。

我遇到错误,问题似乎出在Format-Volume中的盘符名称上。

我在这里https://superuser.com/questions/219401/starting-scheduled-task-by-detecting-connection-of-usb-device

中使用了答案中的大部分脚本
#Requires -version 2.0
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
write-host (get-date -format s) " Beginning script..."
do{
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType)
{
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
}
write-host (get-date -format s) " Event detected = " $eventTypeName
if ($eventType -eq 2)
{
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName
write-host (get-date -format s) " Drive name = " $driveLetter
write-host (get-date -format s) " Drive label = " $driveLabel
Format-Volume -Driveletter "$driveLetter" -NewFileSystemLabel "test" -FileSystem NTFS -Confirm:$false

[media.SystemSounds]::("Hand").play()
}
Remove-Event -SourceIdentifier volumeChange
} while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange

我得到的错误:

2018-10-30T12:45:02  Beginning script...
2018-10-30T12:45:03  Event detected =  Device removal
2018-10-30T12:45:05  Event detected =  Device arrival
2018-10-30T12:45:05  Drive name =  G:
2018-10-30T12:45:05  Drive label =  blabla
Format-Volume : No MSFT_Volume objects found with property 'DriveLetter' equal to ':'.  Verify the value of the property and retry.
At C:\Users\myuser\Desktop\formater.ps1:23 char:1
+ Format-Volume -Driveletter "$driveLetter" -NewFileSystemLabel "test"  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (::Char) [Format-Volume], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound_DriveLetter,Format-Volume

我尝试过:

-Driveletter "$driveLetter"
-Driveletter $driveLetter
-Driveletter ""$driveLetter

但是有网络编码的背景,我真的不知道如何解决这个问题。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

Format-Volume的文档将DriveLetter参数所需的格式显示为Char[]

因此,DriveLetter应该只是驱动器号G,而后没有冒号G:,您可以通过从$driveLetter中仅选择第一个字符来做到这一点:

-Driveletter $driveLetter[0]