Browsing for a file and selecting a Virtual Machine on hyper-v

Hi everyone, sorry if the title is a bit problematic.
New to Powershell here, I'm trying to create a script that will let me Browse for a .vhd file, and then let me select a Virtual Machine to attach it to using SCSI attachment.
So far I managed to attach and detach the VHD files using add-vmharddiskdrive, but using read-host I have to manually enter the address of the .vhd file every time, as well as using read-host to input the VM name.
Is there any way to browse for the file, select it, and then run the add-vmharddiskdrive command?
So far the script I have is this:
$VHDLocation = Read-Host Enter VHD Location
$VMName = Read-Host Enter VM Name
Add-VMHardDiskDrive -VMName $VMName -Path $VHDLocation -ControllerType SCSI
Basically I want to shorten the time it takes to manually type the vhd location and the VM name. Any way to do that?
Sorry for long post, thanks everyone in advance, have a nice day :)

I couldn't get the Select-fromgridview to work sadly, but after snooping around on several different forums I managed to copy-paste some codes and after some work and trial and error I got the script to work perfectly, except for one problem. When the box
pops up to let met select a VM, it pops in the background, as in, behind the ISE itself. So I have to alt tab to see it. Is there any way to make it pop to the front?
I'd go through the script myself but like I said I'm very new to this and honestly most of this could be Chinese for all I know.
Again thanks in advance!
set-executionpolicy unrestricted
############## The script for browsing #############
Function Get-FileName($initialDirectory)
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
 Out-Null
 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
 $OpenFileDialog.initialDirectory = $initialDirectory
 $OpenFileDialog.filter = "All files (*.*)| *.*"
 $OpenFileDialog.ShowDialog() | Out-Null
 $OpenFileDialog.filename
} #end function Get-FileName
############## Sets the VHD location parameter to the selected file from above, and input VM Name  #############
$VHDLocation = Get-FileName -initialDirectory "c:\fso"
############## Select a VM ######
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Select a Computer"
$objForm.Size = New-Object System.Drawing.Size(300,200) 
$objForm.StartPosition = "CenterScreen"
# Got rid of the block of code related to KeyPreview and KeyDown events.
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
# Got rid of the Click event for the OK button, and instead just assigned its DialogResult property to OK.
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$objForm.Controls.Add($OKButton)
# Setting the form's AcceptButton property causes it to automatically intercept the Enter keystroke and
# treat it as clicking the OK button (without having to write your own KeyDown events).
$objForm.AcceptButton = $OKButton
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
# Got rid of the Click event for the Cancel button, and instead just assigned its DialogResult property to Cancel.
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$objForm.Controls.Add($CancelButton)
# Setting the form's CancelButton property causes it to automatically intercept the Escape keystroke and
# treat it as clicking the OK button (without having to write your own KeyDown events).
$objForm.CancelButton = $CancelButton
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Please select a computer:"
$objForm.Controls.Add($objLabel) 
$objListBox = New-Object System.Windows.Forms.ListBox 
$objListBox.Location = New-Object System.Drawing.Size(10,40) 
$objListBox.Size = New-Object System.Drawing.Size(260,20) 
$objListBox.Height = 80
Get-VM | Format-List name | Out-File -filepath c:\VMNames.txt
${C:\VMNames.txt} = ${C:\VMNames.txt} | select -skip 2
function Remove-Topline ( [string[]]$path, [int]$skip=2 ) {
  if ( -not (Test-Path $path -PathType Leaf) ) {
    throw "invalid filename"
  ls $path |
    % { iex "`${$($_.fullname)} = `${$($_.fullname)} | select -skip $skip" }
(Get-Content C:\VMNames.txt) | 
Foreach-Object {$_ -replace "Name :", ""} | 
Set-Content C:\VMNames.txt
Get-Content C:\VMNames.txt | ForEach-Object {[void] $objListBox.Items.Add($_)}
$objForm.Controls.Add($objListBox) 
$objForm.Topmost = $True
# Now, instead of having events in the form assign a value to a variable outside of their scope, the code that calls the dialog
# instead checks to see if the user pressed OK and selected something from the box, then grabs that value.
$result = $objForm.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK -and $objListBox.SelectedIndex -ge 0)
    $selection = $objListBox.SelectedItem
    $selection
    # Do something with $selection
$VMName = $selection.Trim()
############## Dismounts the VHD if it's mounted on host, and then mounts it on VHD #############
Dismount-VHD $VHDLocation
Add-VMHardDiskDrive -VMName $VMName -Path $VHDLocation -ControllerType SCSI
############## Detaches the VHD from VM and returns it to the host #############
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.Interaction]::MsgBox('Press Ok when you are ready to detach the VHD', 'MsgBoxSetForeground,Information', 'Confirm')
Remove-VMHardDiskDrive -VMName $VMname -ControllerType SCSI -ControllerNumber 0 -ControllerLocation 0
Mount-VHD $VHDLocation 

Similar Messages

  • Saving files and future Java Virtual Machine updates questions

    So I've made A program that keeps a list of Ingredients and Recipes for my dads small business. This program is currently on 3 computers my dads, the secretaries, and mine. I made it so it saved and loaded from a shared folder in the network where all the computers has access. The secretary and my dads computer saved and loaded the program fine with changes from one to the other, but mine wouldn't. If I save what information I put on my computer the other computers could no longer load the save file. If i saved something on the secretary or dads computer then my computer would not be able to load the file.
    well i solved this problem by re downloading Java virtual machine on my computer.
    this brings me to my question:
    Will future virtual machine updates make it so the program can't read old .dat files (I've been using ObjectInputStreams and ObjectOutputStreams to save and load)
    Sorry for the long story before the question I just wanted to state how I came to the question.

    Yes, absolutely. That is one of the problems with using serialization to save data. Fortunately the serialization tutorial mentions it and explains some strategies for minimizing the problem. So have a look at that tutorial.

  • Right-click on browser.xul.error_pages.expert_bad_cert and select Toggle. The value will change to true.

    I am working with Firefox 30. I get a certificate error on each webpage I go to. I have reset and uninstalled the browser to no luck. I have also did the following:
    Open a new Firefox window, and type this into the address/URL:
    about:config
    - You'll probably see a warning that changing the config can be dangerous. Click the button to accept the warning and proceed, but BE CAREFUL from here on!
    - A table will appear showing various Firefox settings ("Preference Names") and their current values.
    - In the Filter box type: broswer.xul
    - There should now be a shorter list of settings, including one named browser.xul.error_pages.expert_bad_cert with a value of false.
    - Right-click on browser.xul.error_pages.expert_bad_cert and select Toggle. The value will change to true.
    - Exit completely from Firefox (i.e. close all windows), and then restart it.
    This has not worked either. Does anyone have any other thoughts?

    Any idea why you are getting these errors?
    If you expand the technical details section of the error page, there should be some kind of explanation or code there. Can you copy/paste that into a reply?
    If it says something along the lines of "sec_error_unknown_issuer" this can indicate one of these situations:
    (1) Incomplete security software installation
    Some security suites include a feature to intercept and scan your web traffic, including secure connections. In order to do this, they must present a fake certificate to Firefox, which of course, Firefox rejects. Programs such as ESET and Kaspersky provide a way to either turn off this feature, or import a master certificate into Firefox so that Firefox will trust these programs.
    Does that sound relevant?
    (2) Malware
    Unfortunately, some malware also will intercept your secure connections. Often they can do this invisibly in IE and Chrome because they can inject certificates into the shared Windows certificate store. Because Firefox uses its own certificate file, you may get errors in Firefox that you do not get in IE and Chrome.
    To distinguish these, it's helpful to inspect the "Issued by" section of one of the certificates from a site that works in IE but not Firefox.
    When you get the error page in Firefox, you can expand the "I understand the risks" section, and click the button to Add Exception. You don't need to actually save an exception to inspect the certificate, so you can cancel after viewing the certificate.
    Check the "Issued by" section to see what you find there. For example:
    * Name associated with your security software, such as ESET, BitDefender, Kaspersky, etc.
    * Sendori (indicates unwanted software from Sendori)
    * FiddlerRoot (indicates unwanted software named similarly to BrowserSafeguard, BrowserSafe, SafeGuard)
    * Something else
    What do you see?

  • Word 2010 to PDF hyperlink opens browser for local file...

    Recently upgraded to Office 2010.  I used the Save As .pdf option in Word 2010 for a file that contains a hyperlink to a local pdf file. When I open the saved pdf file with Acrobat Reader and click on the link, my default browser starts up to display the local file. I have tried using different versions of Acrobat Reader, different operating systems, and all kinds of options, but can't figure out why this is happening. I think it's a bug in Word 2010, but can't find any information about this on the web.
    Does anyone have any clues?

    OK, replying to my own post, I did just find a Workaround
    that's only a few extra steps.....
    After all edits and changes were completed in the Word file, I printed to PDF from Word,
    creating a Rev A file. Once that was done and a new pdf was created, I opened the
    Original File and selected "Combine" from the "File" pull down menu.
    With both of the files in the same PDF document, I deleted all the pages from the
    Original file. Page one of the Rev A file is now p. 1 of the "combined" file,
    and all the PDF bookmarks (still there from the Original File) line up in the right
    sequence. The bookmarks (produced by "Saving to PDF" with Headings 1 and 2,
    when the original PDF was made) need to be re-linked to the pages in the Rev A
    file, but that's quicker than starting from scratch.
    Not really very elegant, but it worked. I'd be curious to know what's wrong with the
    PDF files saved with bookmarks in WORD, because that happens EVERY time.
    I have Acrobat Pro Extended, iteration 9.5.1

  • I am running 4.0.1 and when I download something the Download box stays blank-even though I have selected in General Preferences 'Show the downloads window when downloading a file' AND selected 'Save files to Downloads'....???

    I am running 4.0.1 and when I download something the Download box stays blank-even though I have selected in General Preferences 'Show the downloads window when downloading a file' AND selected 'Save files to Downloads'....???

    In Firefox Options / Privacy be sure "Remember download history" is checked. To see all of the options on that panel, "Firefox will" must be set to "Use custom settings for history".
    To find your OS information, on your Windows desktop, right-click the My Computer icon, choose Properties, under System on that small window is info about your OS.
    '''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.'''

  • ITunes crashes while browsing for .ipsw files?

    Hello,
    I have been trying to update my iOS for my iPod touch 4g and iPhone 4 to 5.0 for quite some time.  My first issue was that the connection would fail or timeout every time no matter what (I'm in a country with slow internet at the moment; no way to change that), so I solved that by downloading the .ipsw files online for the respective products. Now that I have them, when I hold shift and click restore or update (i have windows 7) to browse for the files, iTunes stops working.
    the situation with it was: appcrash  objc.dll
    I've uninstalled everything apple related from my computer and re-installed it, and still no success. Short of sending to back the states, does anyone know what I could do to update my iProducts?
    Thank you.

    mmm, my son wants a video iPod for his birthday and I have been checking the 5th gen iPod forums:
    http://discussions.apple.com/category.jspa?categoryID=157

  • Attachments dont download from Gmail in Safari, They disappear,I even tried re-downloading Safari and that download disappeared, it is not in my downloads folder, I actually searched in finder for the file and it is nowhere on my computer.  Please help!

    Attachments dont download from Gmail in Safari, They disappear,I even tried re-downloading Safari and that download disappeared, it is not in my downloads folder, I actually searched in finder for the file and it is nowhere on my computer.  Please help!

    Oh my gosh I had the EXACT same problem, and for ages I couldn't figure out how to fix it until today. Here's what I did:
    First I went onto my computer, opened itunes, and un-installed tumblr, vine and kik. These were the apps I was having problems with (it said I had them on my phone but, like you, they didn't show).
    Then I went to the itunes store, searched for each one, and it said I could update them so I did (just FYI: for tumblr a window popped up saying "please click ok to confirm you are 17 years or older", so I did that also)
    When I went back to my phone and tried installing them again (still on my computer), it worked!
    I hope this helps, because it was incredibly frustrating. Good luck!

  • Wait for a file and start execute a scenario process

    What is the best way to achive: Wait for a file and then once the file in droped...execute a scenario process.
    Sample scenario:
    - Admin user ftp the file to a target directory on Unix (export/home/odi/input/files)
    - A scheduled scenario package will be running/scheduled daily
    - In the above scenario, The first step is to have one OdiFileWait (with options: Dir:/export/home/odi/input/files, File: xxxxx.txt,wait time and loop over..etc)
    /* But for some reason OdiFileWait is not waiting/checking for the file presence define in the option. It seems to run immediately without checking the presence of the file and passing it to run the second step) */
    - The second step is the "OdiStartScen" (This will run an interface generated scenario) and since the file doesn't exist as a source to load that this interface uses...its fails.
    What's the common practice to accomplish this? Appreciate your feedbacks…
    Thank you

    Update:
    I increased the timeout and Pollint setting in OdiFileWait option and its working fine now.
    When the file exists (or) ftp within the timeout the process goes to next step (OK). But, say the file doesn't exists and the timeout finished...how do i set a KO to OdiFileWait and stop/complete by existing at that step itself with out failure.

  • 8dot3 filenames not created for Program Files and Program Files (x86)

    Interesting issue we are realizing on Servers deployed from SCCM 2012. 8dot3names are not created for Program Files and Program Files (x86). they are created for other files/folders at the root of C and below Program Files and Program Files (x86). This is
    causing issues when programs are installed and the path is then created with 8dot3 filenames for program files and program files (x86)

    Arg. we just got bitten by this "feature", and it's affecting our security software stack (name starts with M and ends with ee), and some ancient crud too.
    And found this, which suggests a logical reason for 8dot3name to not be present on servers, but, on clients, I think it's a rather gross assumption...
    http://blogs.technet.com/b/josebda/archive/2012/11/13/windows-server-2012-file-server-tip-disable-8-3-naming-and-strip-those-short-names-too.aspx
    Don
    (Please take a moment to "Vote as Helpful" and/or "Mark as Answer", where applicable.
    This helps the community, keeps the forums tidy, and recognises useful contributions. Thanks!)

  • Searching for missing files and damaged photo icon

    I am trying to view photos that I have viewed in this program numerous times before but now when I click on the photos, I get a message that says "searching for missing files". Sometimes, the photo appears with a red icon below it that resembles a wripped photo. Does this mean my photo has been damaged by the program?

    I too have been told to find them on my hard drive but still nothing comes up, I can find the picture name and then do a search, but nothing. I've tried several times and it just keeps saying seach for missing files not found. I can see my collection of pictures, but there blury and then when I try to click on them, it says searching for missing file and it gives me the file name, and then I've tried to go under my search and put that file name in and nothing comes up, I also got NO help from adobe and they want us to buy more products??? They could have warned us somehow on what happens if you move them or try and put them on disc, and that's what happen, I put some on disk or at least thought I did and then realized I didn't want to do that, so I hit the UNDUE and I guess it was so late or something, cuz I can see the pictues, just can't open them. I'm wandering if I need to have a expert see if he can get them off of Adobe, I really want the pictues I have graduation pictures on there and need them very much. Would love to have help from anybody. Please.
    Thank you
    K

  • Acrobat X: Hotkeys for "hand tool" and "select tool"?

    In Acrobat X, are there hotkeys for "hand tool" and "select tool"?

    thanks.  but why doesn't adobe simply call it "single-key hotkeys"?  "accelerators"??  how ambiguous.

  • The specified file or folder name is too long,the url path for all files and folders

    The specified file or folder name is too long,the url path for all files and folders must be 260 character or less
    can we increase this limit?
    MCTS,ITIL

    Hi,
    As I understand, you want to increase the length of URL path in SharePoint 2010.
    Per my knowledge, this limit cannot be increased. SharePoint limits URL length because all relative URL links are stored in the clear forms on the SharePoint content DB and often this links are used as primary keys to link one table with another. Fields
    which are used to store these links (for instance tp_DirName from the AllUserData table) allow storing only 256 characters.
    There are several ways that you can resolve or mitigate URL length problems in the SharePoint Server 2010 environment. The following list provides suggestions:
    1. Upgrade all the end-user browsers to Internet Explorer 8, which has a longer URL length limit.
    2. Use shorter names for sites, folders, and documents and control the depth of the site and folder structures to reduce the lengths of URLs.
    3. If possible or allowed, use ASCII names for sites, folders, and documents. This will avoid situations where the URL will be lengthened by being encoded.
    4. To reduce the risk that the SharePoint Server 2010 end-users will encounter problems because of URL length limitations, we recommend that you apply the following effective limits in the deployment:
    256 Unicode (UTF-16) Code units - the effective file path length limitation, including a domain/server name
    128 Unicode (UTF-16) Code units - the path component length limitation
    More reference:
    http://technet.microsoft.com/en-us/library/ff919564(v=office.14).aspx
    http://sharepointknowledgebase.blogspot.in/2013/04/url-path-length-restrictions-in.html#.VKJN53BJA
    Best regards,
    Sara Fan

  • FYI Update Rollup 3 for Microsoft System Center 2012 R2 - Virtual Machine Manager (KB2965413) Stops SCVMM service starting

    I just applied update:
    Update Rollup 3 for Microsoft System Center 2012 R2 - Virtual Machine Manager (KB2965413)
    and (KB2965414) but it failed to install.
    After a reboot I could not login to the VMM and the service would not start
    An event id 0 was reported with:
    Service cannot be started. System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
       at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
       at System.Reflection.RuntimeModule.GetTypes()
       at System.Reflection.Assembly.GetTypes()
       at Microsoft.VirtualManager.Remoting.IndigoSerializableObject.BuildKnownAssemblyTypes(Assembly assembly)
       at Microsoft.VirtualManager.Remoting.IndigoSerializableObject.InitializeKnownTypesCache(List`1 assembliesToExamine)
       at Microsoft.VirtualManager.Engine.Remoting.IndigoServiceHost.InitializeKnownTypesCache()
       at Microsoft.VirtualManager.Engine.VirtualManagerService.TimeStartupMethod(String description, TimedStartupMethod methodToTime)
       at Microsoft.VirtualManager.Engine.VirtualManagerService.OnStart(String[] args)
       at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
    After I removed the update the VMM was able to start, no reboot required.
    When I have time I will try to apply both updates again successfully and see if the issue still occurs.
    Vista Ultimate Dell XPS M1330

    FYI.  I've had the same issue after I installed Update Rollup 3 (KB2965413), seeing the exact same error on event log.  Tried to start the service manually, getting service unable to start error.  This is a machine running
    with Windows Server 2012 Standard.  Solution for me is simple. I just install
    KB2965414 (Update Rollup 3 for SCVMM 2012 R2), reboot the server, and the SCVMM service auto start up by itself. 

  • Is there any report in SCCM 2012 to list out all the physcial machine and all the virtual machine?

    Is there any report in SCCM 2012 to list out all the physcial machine and all the
    virtual machine?
    and list all VMs for each physical server.

    Hi,
    there is no such builtin report but you can easily crete one as all information is in the database.
    http://www.scconfigmgr.com/2014/01/24/create-custom-reports-for-configmgr-2012-with-report-builder/
    Regards,
    Jörgen
    -- My System Center blog ccmexec.com -- Twitter
    @ccmexec

  • How to Allow microphone and all hardware in Virtual Machine using Hyper-v

    I have recently installed Windows 10 preview in Windows 8.1 pro.
    How i can allow Microphone and all things in virtual machine from Hyper-v
    Thanks
    Thank You , Shan Ali Khan

    You connect to the VM using the RDP Client - connecting to the IP / name of the VM over the network.
    This enabled all device redirection by default.
    You can possibly use Enhanced Session Mode as well.  That again uses RDP under the hood.
    Brian Ehlert
    http://ITProctology.blogspot.com
    Learn. Apply. Repeat.

Maybe you are looking for