Passing string variable as Argument in Powershell -
i'm trying write powershell script change drive letter of i: else. here's script.
$drivei = get-wmiobject -class win32_volume -filter "driveletter='i:'" if ($drivei.serialnumber=""){ write-host "i: free..." } else { write-host "i: occupied" foreach ( $s in @("'z:'", "'y:'", "'x:'", "'w:'", "'v:'", "'u:'", "'t:'", "'r:'", "'q:'", "'p:'", "'o:'", "'n:'", "'m:'", "'l:'", "'k:'", "'j:'", "'h:'", "'g:'", "'f:'", "'e:'", "'d:'", "'b:'", "'a:'")) { $testdrv = get-wmiobject -class win32_volume -filter "driveletter=$s" if (!$testdrive.exist) { $s = '"'+$s.trim([char]0x0027)+'"' set-wmiinstance -input $drivei -arguments @{driveletter=$s} write-host i: has been moved $s break } } }
allow me walk through script. $drivei
used retrieve information regarding i:. now, if i: has no serial number, indicates i: doesn't exist. if, on other hand, i: exists, i'm trying find drive letter free. i'm implementing search foreach
loop. now, when call get-wmiobject
, use drive letters single quote. when use set-wmiinstance
, use double quotes. however, when modify $s
wrapped double quote, doesn't work. in short, if use write-host $s
, in output, say, "e:"
. when use set-wmiinstance -input $drivei -arguments @{driveletter="e:"}
, works. when use set-wmiinstance -input $drivei -arguments @{driveletter=$s}
, doesn't work. tell me i'm doing wrong?
don't put quotes in strings when you're going remove them later anyway. instead add quotes need them:
$driveletters = 'z:', 'y:', 'x:', ..., 'd:', 'b:', 'a:' foreach ( $s in $driveletters ) { $testdrv = get-wmiobject -class win32_volume -filter "driveletter='$s'" if (-not $testdrv) { set-wmiinstance -input $drivei -arguments @{driveletter=$s} write-host "i: has been moved $s" break } }
Comments
Post a Comment