Quantcast
Channel: Hey, Scripting Guy! Blog
Viewing all 3333 articles
Browse latest View live

PowerTip: Use a destructive PowerShell cmdlet safely

$
0
0

Summary: Use the –whatif parameter with PowerShell cmdlets to test code live.

Hey, Scripting Guy! Question I heard that PowerShell has a built-in safety switch to many of its cmdlets. Could you show me an example of it in use?

Hey, Scripting Guy! Answer No problem. You’re referring to the –whatif parameter, which is meant to show you what would happen if you used a PowerShell cmdlet without actually executing the cmdlet. An example of this in action is in the following Remove-Item cmdlet.

This will attempt to remove the document, HSG-Article-Sean-Should-Not-Lose.docx, without actually removing it.

Remove-Item .\HSG-Article-Sean-Should-Not-Lose.docx -WhatIf

The Doctor


Erase files based on date by using PowerShell

$
0
0

Summary: Honorary Scripting Guy, Sean Kearney, relates his first experience with PowerShell.

Hey, Scripting Guy! Question I was curious just how difficult it is to use Windows PowerShell. For example, how difficult is it to erase files based on the current date?

Hey, Scripting Guy! Answer Honorary Scripting Guy, Sean Kearney, is here today, and I can completely relate to exactly what you’ve said. I once had absolutely zero time to learn about scripting or automation. I was a field technician.

You know the typical work for some field techs. You get in the car, go to the call, hop back in the car, off to the next call, lunch in a drive-thru, sleep in a parking lot. Also, factor in about five to six hours lost to commute.

Imagine a schedule like that for seven+ years and  when do you have time to learn? I believed exactly the same thing about Windows PowerShell until I found myself in a position where I had to use it.

I clearly remember the day, too. It was sometime late in 2007. I got a call from a client. “There’s a vendor application filling up the server with logs. Please find some way to get rid of the old data. Anything over 24 hours old is garbage.”

“Okay,” I thought to myself. “I’m not a developer or coder, but maybe there’s a utility on the Internet, something from Sysinternals. If I have to spend two hours to learn how to write something, I’ll do it.”

Well, I got on the site, and the first thing that I did was hit the local search engines for “Erase old files based on date” (or something along those lines). I ran into an article on Hey Scripting Guys that showed how to remove files over seven (7) days old from a folder.

It showed this line in PowerShell to get a list of the files ending in .LOG:

Get-Childitem C:\Foldername\*.LOG

It then showed two additional lines to remove that content. One line grabs the current date, and the other filters the list.

$Now=Get-Date

Get-Childitem C:\Foldername\*.LOG | Where-Object { $_.LastWriteTime –lt $Now.AddDays(7) }

I didn’t really understand much other than, “There’s a folder, and this is supposed to show stuff over seven days old. I wonder if I just change that 7 to a 1?”

At that point, I installed PowerShell on a test machine and copied the folder structure that I had to purge. I then made a second copy because the network was slow that day, and I didn’t want to waste time.

I edited the folder name to match the folder that I wanted and the file extension. I also changed that 7 to a 1 and crossed my fingers.

$Now=Get-Date

Get-Childitem C:\VendorApp\*.TXT | Where-Object { $_.LastWriteTime –lt $Now.AddDays(-1) }

I blinked and looked. It displayed only files that were older than today and that had the TXT extension. I was floored. To learn how to remove them, I was ready for a long, drawn-out session. “Grumble grumble…I’ll bet VBScript is involved here somewhere.”

To remove the files, I saw only one extra bit of data. Something called Remove-Item seemed a pretty sensible name. I appended the last bit of code and read a bit further as the article described how to test it without doing anything dangerous by using the whatif parameter.

I shook my head and muttered something about “Pigs flying before this would work,” but I tried it anyway.

$Now=Get-Date

Get-Childitem C:\VendorApp\*.TXT | Where-Object { $_.LastWriteTime –lt $Now.AddDays(-1) } | Remove-Item –whatif

Staring and blinking at the screen of output, I scrolled up. It looked like something happened to the data. But, upon examining the folder, nothing happened. It really did a “What if I do this?”

To actually do the damage, it asked me to remove the –whatif and run the cmdlet.

$Now=Get-Date

Get-Childitem C:\VendorApp\*.TXT | Where-Object { $_.LastWriteTime –lt $Now.AddDays(-1) } | Remove-Item

“Wow!” Staring at the folder, I was speechless. Only 24 hours files left of files ending in TXT.

I had been on site for only 10 minutes, and the problem was solved….almost.

“I’ll bet this won’t work on the server,” I thought. I was ready for the worst. This was my first time using PowerShell and I was untrusting.

So, repeat process, install PowerShell 1.0 on the Windows Server 2003 R2 environment, copy this script, duplicate the folder of data. After all, I wasn’t about to see how good their backup system was.

I tested the process, and the results were the same. Now I had to figure out how to schedule this. Oh, this was like DOS. Instead of running cmd.exe or command.com, it was PowerShell.exe.

I made a little folder called “C:\DataClean”, saved this new script called LogClean.PS1, and set up a scheduled task.

PowerShell.exe –executionpolicy Bypass –file C:\DataClean\LogClean.PS1

I ran the task and crossed my fingers.

POOF! It all just worked!

I was on site for barely 20 minutes for a two-hour minimum billable call. I was also on the road early and beat rush hour traffic on a Friday.

Hearing AC/DC’s Highway to Hell on the radio and with the knowledge of what technology got me home early that day, I began singing loudly all the way home. Singing to the chorus of the song, the words “I’m using PowerShell! I’m using PowerShell!” kept bursting from my lips.

Yes, I love using PowerShell. Over the next while, I’ll try to relate some things that you can use PowerShell for without needing to learn how to script.  Even if you, too, are that field tech with no time on your hands.

I invite you to follow the Scripting Guys on Twitter and Facebook. If you have any questions, send email to them at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow.

Until then, always remember that with Great PowerShell comes Great Responsibility.

Sean Kearney
Honorary Scripting Guy
Cloud and Datacenter Management MVP

PowerTip: List all subfolders under a target path with PowerShell

$
0
0

Summary: Use Get-Childitem to provide a printable list of all folders under a path.

Hey, Scripting Guy! Question I used to use tree.com to get a list of folders on a computer. Is there something close to that in PowerShell? Maybe something I could print?

Hey, Scripting Guy! Answer If you were to use Get-Childitem combined with Select-Object, you could get a pretty clean list. Here’s an example that targets drive c: and all hidden folders. It displays only directories and their full paths.

Get-ChildItem -Path C:\ -Recurse -Directory -Force -ErrorAction SilentlyContinue | Select-Object FullName

The Doctor

Use Windows PowerShell as an administrative console

$
0
0

Summary: Honorary Scripting Guy, Sean Kearney, shares his early use of PowerShell as a network administrator.

Hey, Scripting Guy! Question I have a simple but irritating task each day around lunch time. A handful of people usually lock themselves out of Active Directory. Can you help me find an easy way to deal with this?

Hey, Scripting Guy! Answer Honorary Scripting Guy, Sean Kearney, is here to help you share the pain. I, too, once felt that prickly feeling on the back of my neck near the end of lunch hour. “Lock out Hell”, I called it.

I know that everyone has experienced that, especially on Friday. A handful of people come in and for whatever reason have locked themselves out.

We’re not even going to get in to the root cause of this: the Shift key was stuck, there was a soft lock in the software, or their brains were sucked away by Martians.

Perhaps they were showing off their ‘R@s K001 P@$$w0rd skillz’ to a co-worker and incorrectly typed the last three punctuation marks in the password they invented.

But, you would almost always get an onslaught of “I locked myself out and NEED (not want … capital N*E*E*D) to get back in now.”

In the old world, I would have had to go to Active Directory Users and Computers, find the user, unlock the user, call the use, and then proceed to the next person.

But, it never works like that, does it? Invariably, some of those users (or maybe all on a bad day) will lock themselves out again in that same 10-minute period. Thus the phrase, “Lock out Hell”, as you waste half an hour going through the GUI to unlock users.

People make mistakes, and there’s no use getting angry with them. The process itself was just, well, lacking finesse.

I had been using PowerShell earlier that month to migrate users to a new Active Directory and had been playing with the Quest cmdlets at the time. One lunch hour, I played with PowerShell and found the Unlock-QADUser cmdlet.

After I found this cmdlet, the process was simply a matter of running something like the following for the five or six people:

Unlock-QADUser jsmith

Then I pressed an up arrow, entered the next name, and repeated the process for the next four or five. It was far less stressful. In the modern Windows Server 2008 R2 and higher environment, I would have used the following cmdlet:

Unlock-ADAccount

It accomplished the same result and, again, was far less aggravation for everyone…including me. :)

Later on, I would have to start disabling users, often quietly and discreetly. Very much like “Shh…when you see your phone ring from the VP Disable Mr. X.”  (Professor Xavier’s evil cousin, you see.)

For that, it was a matter of queuing up a cmdlet like Disable-QADUser. I would also correspondingly have an Enable-QADUser ready because sometimes it was actually Mrs. Y and not Mr. X so “Could you please quickly flip that around?”

As result, it was very easy to deal with those situations by using PowerShell just as a management console.

Later on in my IT life, we had to start producing some basic audits about who had Domain Admin and Enterprise Admin access. I already knew that I could use PowerShell to ask Active Directory questions, such as, “Show me all the members of this group.”

Auditors who saw the code that did the audit were very happy to see that it was PowerShell. The following cmdlet pulled up a list of Domain Admins and dumped it untouched to a CSV file.

Get-ADGroupMember -Identity 'Domain Admins' | Export-CSV DomainAdmins.csv

My environment actually had quite a few domains. Some were for the Development division, Vendor applications for a customer. Because of PowerShell, it was easy to pull the same data for any environment from the console.

As my work progressed into other environments, including managing my remote workstations, PowerShell was my view into systems. Using Windows Management Instrumentation (WMI), I would easily query a remote system for its serial number by using Get-Wmiobject:

(Get-WmiObject win32_bios –computername PC123).serialnumber

At the time, I didn’t have tools like System Center Configuration Manager. Our Division was pretty small. I still needed to manage systems and ask questions.

Those questions were readily answered by using PowerShell, even without scripts.

It’s just some food for thought if you’re convincing yourself that PowerShell is only for scripters.

Pop on in tomorrow. If you’re curious, I’ll show you some neat tricks that Microsoft offers to use PowerShell without actually have to learn it.

Strange concept, eh?

I invite you to follow the Scripting Guys on Twitter and Facebook. If you have any questions, send email to them at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow.

Until then, always remember that with Great PowerShell comes Great Responsibility.

Sean Kearney
Honorary Scripting Guy
Cloud and Datacenter Management MVP

PowerTip: List all available CIM classes by using PowerShell

$
0
0

Summary: Use the Get-CimClass cmdlet to see all classes that you can query from.

Hey, Scripting Guy! Question How can I find a list of Common Information Model (CIM) classes in Windows so that I can ask my computer useful questions?

Hey, Scripting Guy! Answer Just run the Get-CIMClass cmdlet to get a list of all available classes in the default namespace in Windows. If you’d like to filter on the list, you can use a wildcard. In the following example, we show all classes that begin with Win32 and have the word, Disk, in it.

Get-CimClass Win32*Disk*

The Doctor

Find ready-to-use sample PowerShell scripts in the GUI

$
0
0

Summary: Honorary Scripting Guy, Sean Kearney, goes over some often missed, easy-to-use PowerShell techniques for those who are starting out.

Hey, Scripting Guy! Question I had heard a rumor that many of the management tools actually run PowerShell code in the backend. Is there any way to see what code it’s running?

Hey, Scripting Guy! Answer Honorary Scripting Guy, Sean Kearney, is here today, and, yes, it’s true. This hidden gem is one of the most frequently missed pieces by many people who use PowerShell. The GUI in many cases is calling up PowerShell.

Let’s begin with something pretty simple: managing users in Active Directory and auditing groups. For me, that’s a pretty standard, day-to-day task for most administrators.

A lot of people currently use Active Directory Users and Computers. It’s very fast and efficient. However, if you haven’t looked at the Active Directory Administration Center in Server 2012, you’re missing out on a gold mine!

This particular tool passes everything through PowerShell while you still work in the GUI. Here’s an example. Let’s pretend that my boss said, “Hey, who in our network has domain admin access?”

In the Active Directory Administrative Center, I can search for a property in the Global Search context. Here I search for the group domain admins.

Screenshot of the Active Directory Administrative Center with “domain admins” in the “Global Search” field.

When I press Enter on the found object, I can see the properties of that object.

Screenshot of the properties of the Domain Admins group.

In this case, there is only one member. I’m going to show you something about PowerShell here. Every single action is logged as a PowerShell cmdlet.

To view how this process was done in PowerShell, you need to look down on the bottom to see the words, WINDOWS POWERSHELL HISTORY. Click the little arrow to expand the window.

Screenshot of the arrow that expands the window to show PowerShell history.

This will expand a log window. You might not see anything until you select the Show All box.

Screenshot that shows the “Show All” option.

Click the Clear All tab and do something basic in the console, such as viewing that same group again. When you do that, some information will appear in the window.

Screenshot that shows PowerShell commands that correspond to functions in the GUI.

This is your search for the group in the console, followed by accessing the group, and then the group membership. This is the PowerShell code that did the work for you.

If you’d like to grab the PowerShell code to play with or to use again, just click the code, and then choose your favorite “Copy All Combo” – CTRL-A, CTRL-C.

Screenshot of selected PowerShell code.

You can then paste the code directly into Notepad for safekeeping. You can also paste each individual line into an open PowerShell console to see what each line does. This console alone is a pretty good way to use the GUI and get the PowerShell code to play with on your own.

In the following sample, the Get-ADGroupMember content from the console was pasted and run in a PowerShell console.

Screenshot of results from running Get-ADGroupMember in the PowerShell console.

This same technique works for almost anything you do in the Active Directory Administrative Center including disabling and unlocking accounts. It gives you the option to use PowerShell for some regular tasks without having to learn the code part.

Another great example is the Microsoft Deployment Toolkit, which is just ripe with automation in both VBScript and PowerShell. It offers a feature that you’ll often find in GUI-based applications from Microsoft.

It’s the mythical, magical View Script box that you may have been overlooking during your wizards.

Here in the Microsoft Deployment Toolkit, we’ll do a basic import of a driver from the C:\Drivers folder.

Screenshot of the “Import Driver Wizard” where you provide a path to a driver.

Screenshot that show a summary after you provide a path to a driver.

As you continue, the wizard will import the drivers from the source folder to the Microsoft Deployment Toolkit. If this task were very long, a problem is that the process would tie up the Microsoft Deployment Toolkit console until it was done.

Screenshot of progress bars in “Import Driver Wizard” as it completes an import.

At the very end, you’ll notice something you might have overlooked: the View Script button.

Screenshot of the “View Script” button.

If you click View Script, you will see the actual PowerShell code that performed this operation. Here’s the example from the action where we imported the driver.

Screenshot of the PowerShell code that imported the driver.

So, even if you don’t know how to code in PowerShell, you can see the “C:\Drivers” folder. If you needed to add more drivers to the same structure, you could change “C:\Drivers” to the new source folder easily. If you just pasted the code into PowerShell right now, you’d notice something.

Screenshot of the result from pasting code to import a driver in the PowerShell console.

First, it does the action again and warns a lot about “Already existing.” The second and more critical piece is that the console is not tied up during this process.

Think about when you update media in the Microsoft Deployment Toolkit. Wouldn’t this be handy? It also means that although you didn’t learn how to script in PowerShell, you learned how you could make PowerShell useful for you.

Interesting thought, eh?

Other applications, such as System Center Virtual Machine Manager, do this as well. Keep your eyes out for various applications that contain View Script. You may just find some hidden gold in there!

Stop on by tomorrow when Honorary Scripting Guy, Will Anderson, shows us a neat solution that he found to a problem he encountered in Azure Resource Manager!

I invite you to follow the Scripting Guys on Twitter and Facebook. If you have any questions, send email to them at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow.

Until then always remember that with Great PowerShell comes Great Responsibility.

Sean Kearney
Honorary Scripting Guy
Cloud and Datacenter Management MVP

PowerTip: Get a GUI interface for any PowerShell cmdlet

$
0
0

Summary: Use the Show-Command to build PowerShell cmdlets.

Hey, Scripting Guy! Question I ran into a problem. Some cmdlets have too many parameters to list. Is there an easy way to build a cmdlet with its parameters for the console?

Hey, Scripting Guy! Answer You’ll love this trick! Just use the Show-Command cmdlet with any PowerShell cmdlet to get a GUI interface. In the following example, we use this with the Import-MDTDriver cmdlet.

When you are done, you will have three options: Run, Copy (for the clipboard), or Cancel.

Show-Command Import-MDTDriver

The Doctor

How to alter the public IP address of an Azure virtual machine

$
0
0

Summary: Change the public IP address in Azure Resource Manager by using Windows PowerShell.

Honorary Scripting Guy, Will Anderson, shares a personal challenge that he encountered when working with Azure and public IP addresses. He also shares the solution with the rest of us!

Take it away, Will!

Recently, I incorrectly configured an Azure Resource Manager virtual machine (VM) in my lab environment and needed to make some changes to the public IP settings. A brief look around the Internet came up empty, so I thought I’d share the challenge and the solution to this puzzle with you.

The challenge

If we take a look at Set-AzureRmPublicIpAddress, it uses only one parameter: -PublicIPAddress. To actually change the properties in the object, however, we need to call them. How do we do that? It depends on the property in question, so I’ll give you an example of two different properties that we’re going to change on our target VM. In this example, we’re going to change our public IP allocation from Dynamic to Static, and we’re going to give our PublicIP a friendly name and a fully qualified domain name (FQDN).

Data formatting or using an existing example

We can look up an existing PublicIP configuration by doing the following:

$ExResGrp = Get-AzureRmResourceGroup -Name 'lwindsc'

$PubIP = (Get-AzureRmPublicIpAddress -ResourceGroupName $ExResGrp.ResourceGroupName).where({$PSItem.Name -eq 'lwindsctgtwestuspubip'})

And as we can see, we have a configuration to look at:

Screenshot of results that show an existing PublicIP configuration.

The PublicIpAllocationMethod, where we define our configuration as Static or Dynamic, is a simple string, which is easy enough to pass along. But, if you notice, the DNSSettings are displayed in a hashtable. So, let’s construct our changes. First, we cast our target PublicIP configuration object to a variable:

$TgtResGrp = Get-AzureRmResourceGroup -Name 'lwinpubip'

$PubIP = Get-AzureRmPublicIpAddress -ResourceGroupName $TgtResGrp.ResourceGroupName

If we call the object, we’ll see that the PublicIpAllocationMethod is set to Dynamic, and the DnsSettings property is null

Screenshot that shows that the PublicIpAllocationMethod is Dynamic and the DnsSettings property is null.

Make the change

Now we call the properties that we want to modify and the values that we want to input.

$PubIp.PublicIpAllocationMethod = 'Static'
$PubIP.DnsSettings = @{

'DomainNameLabel' = ($TgtResGrp.ResourceGroupName + $TgtResGrp.Location + 'pubip')
'Fqdn' = ($TgtResGrp.ResourceGroupName + '.westus.cloudapp.azure.com')

}

If we look at our stored object, we can see the changes that we’ve made:

Screenshot that shows that the PublicIpAllocationMethod is changed to Static and the DnsSettings property is no longer null.

Now we commit the changes to Azure by passing our object back with Set-AzureRmPublicIpAddress.

$PubIP | Set-AzureRmPublicIpAddress

Screenshot that shows results after pass the object back with Set-AzureRmPublicIpAddress.

And now our system is accessible remotely by a friendly name!

Thanks, Will, for sharing that with the community! I’m certain you’ve made somebody’s day!

I invite you to follow the Scripting Guys on Twitter and Facebook. If you have any questions, send email to them at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow.

Until then, always remember that with Great PowerShell comes Great Responsibility.

Will Anderson
Honorary Scripting Guy
Cloud and Datacenter Management MVP


PowerTip: Get the public IP of an Azure VM with PowerShell

$
0
0

Summary: Use the Azure Resource Manager cmdlets to get the public IP address of an Azure virtual machine.

Hey, Scripting Guy! Question How can I get the public IP address information for an Azure Resource Manager virtual machine (VM)?

Hey, Scripting Guy! Answer All you need to do is use Get-AzureRmVm to find the VM and pass it to Get-AzureRmPublicIPAddress as in the following example:

Get-AzureRmVM -ResourceGroupName ‘HSG-ResourceGroup’ -Name ‘HSG-LinuxVM’ | Get-AzureRmPublicIpAddress

The Doctor

Passing through devices to Hyper-V VMs by using discrete device assignment

$
0
0

Summary: Learn how to attach a device from your Hyper-V host to your VM by using a new feature of Windows Server 2016.

Today we have a guest blogger, Rudolf Vesely, who has blogged here on previous occasions. Here is a link to his previous posts if you would like to read them.

Here is what Rudolf says about himself.

I am an Azure Solutions Architect at Rackspace in London. I believe that public cloud is the future for most organizations and this is why I specialize in public clouds (Amazon Web Services and Azure) and hybrid cloud strategy. My unique role at Rackspace is to guide our customers in their cloud strategy and ensure that their strategy is aligned with their business.

I started my career as a developer and have continued programming and scripting as a hobby. This is the reason why I am a big proponent of DevOps. I believe PowerShell is a fantastic tool that facilitates the process of joining the Dev and Ops worlds.

Contact information:

Introduction

Many new features in Windows Server 2016 (in any Technical Preview) will draw your attention, and it’s very easy to miss some of them. This is true especially when people don’t speak or blog about them too much like they do for Windows PowerShell 5.0, Storage Spaces Direct, or Storage Replica, as examples.

One feature that drew my attention is a new feature in Hyper-V called discrete device assignment. It can be very simply described as a device pass-through feature, the likes of which has existed on other hypervisors for many years.

Microsoft started with device pass-through on Hyper-V with disk pass-through (attaching a physical disk without using VHD / VHDX), but true pass-through came with single root I/O virtualization (SR-IOV) on Windows Server 2012. I recommend that you read John Howard’s excellent blog post series that describes SR-IOV and hardware and system requirements.

On Windows Server 2016, we finally get the ability to directly work with devices on the host and attach them to a child partition (guest VM) without being limited to only networking and storage. This feature was probably built for passing-through graphics processing units (GPUs) in Azure for N-series VMs (GPU-enabled VMs), but we can use it for anything else. Please keep in mind that this is at your own risk. Microsoft will not support your setups, and you may also have very hard security issues. Any device pass-through on any hypervisor opens the possibility to take down the host (for example, by triggering an error on the PCI Express bus) or worse, taking control of your host.

The last thing you need to consider is whether you have hardware to test on it. You need a modern client computer or server that has Intel Virtualization Technology for Directed I/O (VT-d) or AMD Virtualization (AMD-V). I use an industrial mini PC, which will be my new router and wireless access point (all virtualized), but you should be fine with a modern laptop. So, if you’re still reading, activate Intel VT-d in firmware of your testing computer, install the latest Technical Preview of Windows Server 2016, and start with PnpDevice.

PnpDevice module

On Windows Server 2016, thanks to the PnpDevice module, we finally have the possibility to work with hardware without directly touching Windows Management Instrumentation (WMI). The PnpDevice module will be very important for Nano Server and non-GUI servers, so I recommend that you try it.

Get-Command -Module PnpDevice

CommandType Name                  Version Source

----------- ----                  ------- ------

Function    Disable-PnpDevice     1.0.0.0 PnpDevice
Function    Enable-PnpDevice      1.0.0.0 PnpDevice
Function    Get-PnpDevice         1.0.0.0 PnpDevice
Function    Get-PnpDeviceProperty 1.0.0.0 PnpDevice

Let’s take a look what is attached to your system by using:

Get-PnpDevice –PresentOnly | Sort-Object –Property Class

Screenshot of devices attached to the system.

A lot of devices were returned. Now it’s a good idea to choose what should be passed. I do not have multiple GPUs to pass it, but my goal is to virtualize my router and access point, and I have two wireless adapters in mini PCI-e slots. I found that the easiest way to find them is by using vendor ID:

(Get-PnpDevice -PresentOnly).Where{ $_.InstanceId -like '*VEN_168C*' } # 168C == Qualcomm Atheros

Screenshot of result by using the vendor ID.

If you installed drivers on your host for devices that you want to pass through (I did not), you can filter according to Class Net like this (example from my Surface Book):

Screenshot of filtered drivers.

I will assume that you have installed the VM and chosen a device to attach to it. I installed Windows 10 version 1511 because this is the easiest method to test that dual dynamic acceleration (DDA) works. Later I will try replacing Windows with virtualized pfSense (FreeBSD appliance) and DD-WRT (Linux appliance). Especially in FreeBSD, I might have problems with drivers, and I am sure that I will have no issues with drivers in Windows 10.

Let’s get VM object and device object of my Wi-Fi adapter:

$vmName = 'VMDDA1'
$instanceId = '*VEN_168C&DEV_002B*'

$vm = Get-VM -Name $vmName
$dev = (Get-PnpDevice -PresentOnly).Where{ $_.InstanceId -like $instanceId }

Our first action should be to disable the device. You can check Device Manager by typing devmgmt.msc in the PowerShell console to see that the correct device was disabled.

# Make sure that your console or integrated scripting environment (ISE) runs in elevated mode
Disable-PnpDevice -InstanceId $dev.InstanceId -Confirm:$false

Screenshot that shows disabled device in Device Manager.

Mount

Now we need to dismount the device from the host by using the Dismount-VmHostAssignableDevice cmdlet. To specify a location of the device, we need to get a specific property that is not presented in the device object by using Get-PnpDeviceProperty.

locationPath = (Get-PnpDeviceProperty -KeyName DEVPKEY_Device_LocationPaths -InstanceId $dev.InstanceId).Data[0]
Dismount-VmHostAssignableDevice -LocationPath $locationPath -Force –Verbose

Now if you refresh the device object, you can see that something changed: Device is described as “Dismounted”:

(Get-PnpDevice -PresentOnly).Where{ $_.InstanceId -like $instanceId }

You can check available assignable devices by using Get-VMHostAssignableDevice:

Screenshot that shows available assignable devices.

The last step is to attach an assignable device to the VM by using Add-VMAssignableDevice like this:

Add-VMAssignableDevice -VM $vm -LocationPath $locationPath –Verbose

You may get error like this one:

Screenshot of errors.

This is because you haven’t modified the VM configuration after you created it. There are two main requirements for passing through. The first is that the VM has to have Automatic Stop Action set to Turn off the virtual machine. This will probably be the only VM on your host that has this configuration because we usually want Shut down or Save. The second requirement is memory configuration. Dynamic memory is allowed, but minimum and startup memory have to be equal. Let’s fix it, and finally attach our device.

Set-VM -VM $vm -DynamicMemory -MemoryMinimumBytes 1024MB -MemoryMaximumBytes 4096MB -MemoryStartupBytes 1024MB -AutomaticStopAction TurnOff
Add-VMAssignableDevice -VM $vm -LocationPath $locationPath –Verbose

Screenshot that shows AutomaticStopAction is set to TurnOff and memory is configured.

If you spend some time playing with DDA, you can finish, for example, with multiple Wi-Fi adapters and one physical like I did (all functional):

Screenshot that shows multiple Wi-Fi adapters and one physical adapter.

Restore configuration

That was fun! Now it’s time to return devices to the host.

# Remove all devices from a single VM
Remove-VMAssignableDevice -VMName VMDDA0 -Verbose

# Return all to host
Get-VMHostAssignableDevice | Mount-VmHostAssignableDevice -Verbose

# Enable it in devmgmt.msc
(Get-PnpDevice -PresentOnly).Where{ $_.InstanceId -match 'VEN_168C&DEV_002B' } |
Enable-PnpDevice -Confirm:$false -Verbose

Full code

$vmName = 'VMDDA0'
$instanceId = '*VEN_168C&DEV_002B*'
$ErrorActionPreference = 'Stop'
$vm = Get-VM -Name $vmName
$dev = (Get-PnpDevice -PresentOnly).Where{ $_.InstanceId -like $instanceId }
if (@($dev).Count -eq 1) {


Disable-PnpDevice -InstanceId $dev.InstanceId -Confirm:$false
$locationPath = (Get-PnpDeviceProperty -KeyName DEVPKEY_Device_LocationPaths -InstanceId $dev.InstanceId).Data[0]
Dismount-VmHostAssignableDevice -LocationPath $locationPath -Force -Verbose
Set-VM -VM $vm -DynamicMemory -MemoryMinimumBytes 1024MB -MemoryMaximumBytes 4096MB -MemoryStartupBytes 1024MB -AutomaticStopAction TurnOff

# If you want to play with GPUs:
# Set-VM -VM $vm -StaticMemory -MemoryStartupBytes 4096MB -AutomaticStopAction TurnOff
# Set-VM -VM $vm -GuestControlledCacheTypes $true -LowMemoryMappedIoSpace 2048MB -HighMemoryMappedIoSpace 4096MB -Verbose

Add-VMAssignableDevice -VM $vm -LocationPath $locationPath -Verbose

} else {

$dev | Sort-Object -Property Class | Format-Table -AutoSize
Write-Error -Message ('Number of devices: {0}' -f @($dev).Count)

Thank you for reading, and see you in the next article.

Rudolf

Thank you, Rudolf, for sharing your time and knowledge.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. Also check out my Microsoft Operations Management Suite Blog. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

PowerTip: Find all devices connected to a computer

$
0
0

Summary: Use PowerShell to find all devices that are connected to a computer.

Hey, Scripting Guy! Question How can I use Windows PowerShell to list all devices that are connected to a computer?

Hey, Scripting Guy! Answer Use the Get-PnpDevice cmdlet and the -PresentOnly switch. Here is an example:

Get-PnpDevice -PresentOnly

The Doctor

Get started with PowerShell and SharePoint Online

$
0
0

Summary: Microsoft PFE Chris Weaver talks about getting started with Windows PowerShell and SharePoint Online.

Welcome back Chris Weaver as guest blogger. You can see his previous guest blogs.

Christopher Weaver is a Microsoft Premier Field Engineer (PFE) who focuses on SharePoint and Office 365 solutions for large enterprise Premier customers. He has been doing PowerShell and SharePoint with Microsoft for nine years. In his spare time, he enjoys backpacking, hiking, kite surfing, and spending time with his kids and dog. You can follow him on his blog.

Hello All,

I’ve put the kids to bed, the dog is snoring on the couch, and I am thinking about a conversation I had earlier today with one of my customers. He is currently planning to migrate SharePoint 2010 and SharePoint 2013 farms from on-premises to the cloud. The project had a few points to follow:

  • Start by moving ~13.5 TB of data
  • Move site collections from on-premises to the cloud
  • Maintain current budget (in a perfect world)

The current field of migration options to SharePoint Online have three choices, but really only two are popular or regularly used.

  1. Microsoft partner tools

There are several popular ones, which I can’t name, but do a quick Internet search, and I think you will figure it out.

  1. FastTrack team, which is a team here at Microsoft to help customers get their data into the cloud.
  2. PowerShell

There are cmdlets to manage site collections, tenant, and an API to perform upgrades to the cloud.

As you can imagine, the first two options are the most popular because they use a prepared product or let somebody else do it. There are some definite pros and cons to each choice. The FastTrack and PowerShell options can only move list or libraries. You have to create your site collections, webs, and other SharePoint objects, which provides a possible cost savings. Although partner tools work and essentially come with a built in process, they can be expensive. This choice reminds me of a saying. “You can have only two of the following: cheap, well done, or fast, so choose wisely.”

Because I’m writing for Hey, Scripting Guy!, I think we all know which direction we will be going. I plan to write several articles to explain how you can migrate all your data and recreate the site collections and webs. In this article, we will start at the beginning and work our way through connecting to the SharePoint tenant. Here are the system requirements to work with SharePoint Online.

Windows Management Framework 3.0

Note: This is a minimum. It will work on a machine with versions 4 or 5 of Windows Management Framework.

Now that you have a machine to work with, you need to open PowerShell and connect to your SharePoint tenant. To open PowerShell, you can open the regular PowerShell command window or import the SharePoint Online module as I have in the following screenshot.

Screenshot that shows imported SharePoint Online module.

Note: You can safely ignore this message.

If you open the SharePoint Online Management Shell, this essentially opens PowerShell and imports the module for you by using a special profile. Either way you do it, you are now ready to start to manage SharePoint Online.

Now if you run Get-Command -module Microsoft.Online.SharePoint.PowerShell, you should see something like this:

Screenshot that shows result of running Get-Command -module Microsoft.Online.SharePoint.PowerShell.

If you do see this, there is one last step before you can manage tasks like site collection creation, deletion, or administration.

Before we can manage site collections or the SharePoint tenant, you will have to connect to your tenant. To connect you use the Connect-SPOService cmdlet, which requires two pieces of information from you.

  • URL

This is the Admin center URL and, in my case, that is https://mod499144-admin.sharepoint.com.

If you don’t know your URL, go to https://portal.office.com, sign in with your admin account, go to the App Launcher where you should find the Admin app, and click on the app.

Admin app.

On the left side of the page, you will see the Admin Center icon. Select it, and select SharePoint. You will then go to the Admin Center where you can copy the URL from the browser.

Screenshot of the Admin Centers.

  • Credential

This is the username of your administrative account, and the account needs to be a Global administrator. In my case, that is administrator@mod499144.onmicrosoft.com, although yours might be something like admin@contoso.com.

- Screenshot of the Connect-SPOService command and options.

You will be prompted for the password so go ahead and enter that….and, no, I won’t tell you what mine is.

Note: You can only connect to one tenant at a time. If you run Connect-SPOService again, you will disconnect from your current service and connect to another service.

When you’re done managing things and if you want to keep things secure, you need to close the connection to your tenant so you’re going to want to run the Disconnect-SPOService command. The account that runs this command needs to be a Global administrator.

Screenshot of the Disconnect-SPOService command.

Note: Closing the connection to the service does not stop long running processes like a migration.

That’s it for today. I know we are starting slowly, but you need to learn to crawl before you can start sprinting. In my next article, I plan to take you through managing tenants.

Thanks Chris, for sharing your time and knowledge. I look forward to seeing your next article in this series.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. Also check out my Microsoft Operations Management Suite Blog. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

 

The Scripting Guy: coming to a town near you

$
0
0

SUMMARY: The Microsoft Scripting Guys, Ed Wilson, upcoming live appearances.

Hello Scripters,

Teresa (aka. Scripting Wife) here. We have been really busy recently working with PowerShell user groups, and we want to provide you with a convenient listing of upcoming special events. Hope we will be able to see you at one or more of the events. By the way, these events are filling up quickly, so you may want to sign up today. Here is the list:

July:

 July 19, 2016   Tampa FL  SharePoint User Group Meeting

July 21, 2016    Tampa FL   Tampa PowerShell User Group

 August:

August 17, 2016  Basel Switzerland   Basel PowerShell User Group

August 22, 2016   Munich, Germany  PowerShell Monday Germany 2016

August 24-26 , 2016  Berlin Germany   SCU Europe

August 29, 2016   Copenhagen Denmark   PowerShell User Group Denmark

 September:

September 1, 2016  Amstelveen, Netherlands   Dutch PowerShell User Group

September 2, 2016  Cologne Germany  Microsoft System and Service Management User Group

September 5, 2016 Mechelen Belgium  Belgian PowerShell User Group

September 26-30, 2016    Atlanta Georgia    Microsoft Ignite

 

That is it for now!  Hope to see you at one of these events.

 Also we will not be there but another event I am happy to promote is IT Pro Camp in Tampa on August 20th. Mark Minasi is the keynote speaker and there will be lots of good speakers and sessions for you.

 

Viewing all 3333 articles
Browse latest View live




Latest Images