Home > Net >  Save powershell get-disk as variable and the use it in if function
Save powershell get-disk as variable and the use it in if function

Time:11-19

I want to make script run only from a specific usb drive. I want to make variable $drive which has output of get-disk command, and the, if $drive contains my usb serial - make some function.

$drive=get-disk -SerialNumber "980D06056030" | ft SerialNumber

if ( "980D06056030" -eq $drive ) {Write-Host "Yes"}

This doesn`t work =(

CodePudding user response:

You should use SerialNumber property like this.

$drive = (get-disk -SerialNumber "980D06056030").SerialNumber
 if ( "980D06056030" -eq $drive ) {Write-Host "Yes"}

CodePudding user response:

Use Where-Object to filter:

Get-Disk | Where-Object -FilterScript {$_.Serialnumber -Eq "980D06056030"}

Note: First use Get-Disk and confirm the Serial number is displayed on the screen in the properties of USB. Some USB devices does not show Serial number. You could also use where-object to filter the USB devices like:

$USBSerialnum = "980D06056030"
Get-Disk | Where-Object -FilterScript {($_.Bustype -Eq "USB") -and ($_.Serialnumber -Eq $USBSerialnum) }
  • Related