powershell and diskpart - powershell

In short I have a volume that I need to assign a drive letter to (using diskpart). The problem now comes in that the volume does not remain the same. You enter disk part a do a "list volume" and the specific volume would be volume 0, then "exit". Enter again and the do a "list volume" again and this time it is volume 4. And so it continues.
Now if this was done by a person it would not be an issue, however this is an automated task, that will "disconnect" the volume on windows 2003 and used on other servers and mounted again on the windows 2003 server.
I'm trying to write a script in powershell that will be able to identify the volume based on a few unique field(s). The problem comes in that I'm getting stuck on interpreting the output of diskpart's "list volume" command with powershell.
The following command provides the output that I need to work with but there after I'm lost.
cls
$dp = "list volume" | diskpart | ? { $_ -match "^ [^-]" }
$dp | format-table -auto
and this is the output it provides and the volume that I'm looking for is Volume 1.
Volume ### Ltr Label Fs Type Size Status Info
Volume 0 F DVD-ROM 0 B Healthy
*Volume 1 Partition 100 GB Healthy*
Volume 2 E DATA NTFS Partition 547 GB Healthy
Volume 3 C OS NTFS Partition 39 GB Healthy System
Volume 4 D APPS NTFS Partition 98 GB Healthy
Can anybody help me in the right direction here please. I'm at my tether's end.

Yes I got it!!
Here is the answer. Using VB Script I managed to create a script that did what I was looking for, this I then translated to Powershell and below is the script.
$drive = gwmi Win32_Volume | where {$_.DeviceID -like "*b0f012f6-82b1-11df-a41c-001f29e8f0be*"}
$drive.AddMountPoint("T:\")
$drive.DriveLetter = "T:"
$drive.Put_
$drive.Mount()
The Device ID I obtained by running the following script:
# get volumes on this system
$volumes = get-wmiobject Win32_Volume
# display volume info
# There are {0} volumes on this system, as follows: " -f ($volumes.length)
# Iterate through volumes and display information
foreach ($vol in $volumes) {
"Volume: {0}" -f ++$i
"============================="
$vol | Format-List Access,Automount,Availability,BlockSize,BootVolume,Capacity,Caption,Compressed,ConfigManagerErrorCode,ConfigManagerUserConfig,CreationClassName,Description,DeviceID,DirtyBitSet,DriveLetter,DriveType,ErrorCleared,ErrorDescription,ErrorMethodology,FileSystem,FreeSpace,IndexingEnabled,InstallDate,Label,LastErrorCode,MaximumFileNameLength,Name,NumberOfBlocks,PageFilePresent,PNPDeviceID,PowerManagementCapabilities,PowerManagementSupported,Purpose,QuotasEnabled,QuotasIncomplete,QuotasRebuilding,SerialNumber,Status,StatusInfo,SupportsDiskQuotas,SupportsFileBasedCompression,SystemCreationClassName,SystemName,SystemVolume
}
from a post on msdn on the class Win32_Volume.
I hope this might help somebody else Thank you to everybody that help!

You can just use Powershell and WMI to set the drive letter. Shoudn't need diskpart unless you are doing something else (I'm unfamiliar with that tool)
So (assuming you are trying to set the drive letter of the one volume that doesn't have a letter) this should work:
$drive = gwmi Win32_Volume | where {$_.DriveLetter -eq ""}
$drive.DriveLetter = "X:"
$drive.Put()
If you aren't sure about the drive, just query it first and make sure you are only getting the one you want:
gwmi Win32_Volume | where {$_.DriveLetter -eq ""}

Yep. This is a "feature" of diskpart.
Suggestions from MS (not very useful in your case)
Keep the Disk Management console
(Diskmgmt.msc) running while you
process scripts. Or, keep an instance
of the Diskpart.exe utility running
in the background while you process
scripts. When you do this, the volume
numbers should not change between
instances of the Diskpart.exe
utility. Use the volume Label
information instead of the volume
number to track particular volumes.
See bug report here.

Related

Mapping disk number to Cluster Resource in windows server through power shell script

How do I map the disk number with volume in windows powershell script.?
get-disk command results in:
disk_number friendly_name serial_number etc..
get-volume commands results in:
drive_letter friendly_name fstype drivetype etc..
Question 1. Before bringing up volume as a drive letter / mount point name, how do I know if I am working on the right disk?
Question 2. In cluster failover networks, If I have a disk of 10 GB and is made online, Windows automatically assigns Cluster resource name as "Cluster Disk X" when I do Get-ClusterAvaialableResource. Now how do I map the Cluster resource to the disk number?
With the below cmdlets, I find no property/parameter in common.
a)Get-ClusterResource "Cluster Disk X" |Format-List -Property *
b)Get-Disk -Number "Y" |Format-List -Property *
The situation is little twisted, when I have the disks as mount points under Drive Letter Z:
I am more interested in finding solution to Question2).
Need some pointers. Thanks a lot in advance.

Looking for a Powershell Script to check if Volume Shadow Copy is enabled

Sorry for asking, new in PowerShell. Looking for a Powershell Script to check if Volume Shadow Copy is enabled.
Couldn't find any useful and functional script.
Where did you look?
There are a number samples of these all over the web.
For example, using the script downloadable from here:
Get Shadow Copy Statistics
If you use Shadow Copies of Shared Folders (Previous Versions), this
script may help you keep on eye on how much history you have, the
average snapshot size, whether you are hitting storage area limits or
the 64 shadow copies per volume limit.
https://gallery.technet.microsoft.com/scriptcenter/Get-Shadow-Copy-Statistics-79e05a57
You can use it's example to get stats of such items. Meaning, if you get any results, then of course it's enabled.
#Query the local machine
.\Get-ShadowCopyStats.ps1 -ServerName .
#Query a remote machine
.\Get-ShadowCopyStats.ps1 -ServerName FS01
#Query multiple remote machines by passing an array
.\Get-ShadowCopyStats.ps1 -ServerName FS01,FS02
#Since it's the first parameter, you don't have to include -ServerName in the command:
.\Get-ShadowCopyStats.ps1 FS01,FS02
#Query multiple remote machines by passing them to the script down the pipeline
"FS01","FS02" | .\Get-ShadowCopyStats.ps1
Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=company,DC=tld" | .\Get-ShadowCopyStats.ps1 -ShowAllVolumes | Tee-Object -Variable ShadowCopyStats
$ShadowCopyStats | Select * | Export-Csv -NoTypeInformation .\ShadowCopyStats.csv
Or this one...
Get Remote Shadow Volume Information With Powershell
Gather the remote shadow volume information for one or more systems
using wmi, alternate credentials, and multiple runspaces. Function
supports custom timeout parameters in case of wmi problems and returns
shadow volume information, shadow copies, their providers, and
settings.
https://gallery.technet.microsoft.com/scriptcenter/Get-Remote-Shadow-Volume-e5a72619
RemoteShadowCopyInformation -ComputerName 'Server2' -Credential $cred).ShadowCopyVolumes
when the shadowcopy is enabled, there will be a scheduled task created
$allTasks = Get-ScheduledTask
foreach ($task in $allTasks) {
if ($task.TaskName.Contains("ShadowCopyVolume")) {
#get volumeid & drive letter which shadowcopy is enabled
$allVolumes = Get-Volume
foreach ($volume in $allVolumes) {
if ($volume.ObjectId.Contains(($task.TaskName.Split("{")[1]).Split("}")[0])) {
write-host ($volume.driveletter + ":\ is enabled")
}
}
}
}

Net view - get Just ' Share Name'

I need to get all of the shares name in some storage's.
Im using Net view $StorageName and it's show The result in a Table format :
Share name Type Used as Comment
----------------------------------------------------------------------------
Backups Disk
CallRecordings Disk
Download Disk System default share
home Disk Home
homes Disk System default share
Installs Disk
Justin Disk Copy of files from Justin laptop
michael Disk
Multimedia Disk System default share
Network Recycle Bin 1 Disk [RAID5 Disk Volume: Drive 1 2 3 4]
Public Disk System default share
Qsync Disk Qsync
Recordings Disk System default share
Sales Disk Sales Documents
SalesMechanix Disk
Server2012 Disk Windows Server 2012 Install Media
Usb Disk System default share
VMWareTemplates Disk
Web Disk System default share
The command completed successfully.
Thats good, but I need Just the Share Name.
I need Help please.
Thanke You!
Here is one way you could do it with the net view output:
(net view $StorageName | Where-Object { $_ -match '\sDisk\s' }) -replace '\s\s+', ',' | ForEach-Object{ ($_ -split ',')[0] }
Basically that is saying find the lines that have Disk surrounded by whitespace just in case something else might have Disk in the name. Then replace multiple spaces with a comma. Then, for each of those lines, split again by the comma and take the first value which would be the share name.
If you are on a Windows 8/2012 or newer system (and attempting to enumerate shares on other Windows systems), you could use a CIM session along with Get-SmbShare instead of net view which would return the results as objects and allow you to select the fields you want in the native PowerShell way.
For example:
$cimSession = New-CimSession $StorageName
Get-SmbShare -CimSession $cimSession | Select Name
Name
----
Admin
ADMIN$
C$
IPC$
J$
print$
Public
Software
Another option for parsing the net view output that relies on positioning rather than regular expression matching. personally I feel it's a bit easier to read and just as reliable.
function get-shares {
param($server)
$rawShares = net view \\$server
$shares = $rawShares[7..($s.Count - 3)]
$shares | . {process{$_.substring(0,($_.indexof(" ")))}}
}

Powershell: Re-create RDS Remote Apps by Looping?

I'm stumped. I can usually take the output of one powershell command and use it as the input to another powershell command. For example:
Get-Mailbox | Set-Mailbox -MaxSendSize 40MB
This will loop through every mailbox and then set the maximum send size to 40 MB in Exchange 2007.
...but the same doesn't work with get-rdremoteapp and new-rdremoteapp.
Get-RDRemoteApp | new-rdremoteapp -collectionname APPSNEW -connectionbroker edge-1.mydom.local
The goal of this command is that we are preparing to Migrate from a Windows 2012 RDS environment on virtual servers to a Windows 2012 R2 environment on physical servers.
On the virtual 'edge' server, I should be able to get all the RD Remote Apps, loop through them, and then use the 'new-rdremoteapp' command to create them on the new 'edge-1' server.
What actually happens is the command runs and creates the 1st remote app, then exits without an error. It doesn't process the apps in the list.
I think I need to use foreach-object, but after reading the docs and playing around, I can't seem to get it to work.
I couldn't find an easy out. I had to specify a bunch of parameters like so:
Get-RDRemoteApp | foreach-object -process {new-rdremoteapp -collectionname APPSNEW -connectionbroker edge-1.mydom.local -displayname $_.displayname -filepath $_.filepath -alias $_.alias -commandlinesetting $_.commandlinesetting -usergroups $_.usergroups}
Time to find a job that has more bash scripting... ;)

With PowerShell, is there a way to make an external hard disk attached to host available to VM?

I have Hyper-V module installed but don't know what cmdlet to use. I've seen blogs showing how to do this using Hyper-V Manager. I have added a VHDx disk image with following cmdlet:
Add-VMHardDiskDrive -VMName MyWin7PC -ControllerType IDE -ControllerNumber 0 `
-ControllerLocation 0 -Path "C:\Virtual Hard Disks\VDisk.MyWin7PC.Vhdx"
What I now need is a way for VM to have another drive E: which will show files and folders the host has on its G: drive (which is physically connected to a USB hard disk). I need this temporarily to install applications from the USB hard disk. You can do this using the Hyper-V Manager GUI.
I don't use Win8, so this is entirely untested. Judging from the description of Add-VMHardDiskDrive something like this might work, though:
$usbdisk = gwmi Win32_DiskDrive | ? { $_.PNPDeviceID -like 'USBSTOR\*' }
Add-VMHardDiskDrive -VMName MyWin7PC -ControllerType IDE -ControllerNumber 0 `
-ControllerLocation 1 -DiskNumber $usbdisk.Index
You have to make this disk Offliine. Try this:
"select disk 1","offline disk" | diskpart
Where 1 is your USB HD id. And then use Add-VMHardDiskDrive. If you want to do this when VM is online you must use SCSI Controller in VM.