Skip to main content
How to enable promoted links in publishing portal site
PowerTip: Use PowerShell to Write BitLocker Recovery Key to Text File
Summary: Use Windows PowerShell to write your BitLocker recovery key to a text file.
If I forgot to save my BitLocker recovery key when I enabled BitLocker on my laptop, how can I use Windows PowerShell to write it to a text file so I can copy it to a USB key for safe keeping?
From an elevated Windows PowerShell console, use the Get-BitLockerVolume function, select -MountPoint C, choose the KeyProtector and the RecoveryPassword properties, and then redirect the output to a text file:
(Get-BitLockerVolume -MountPoint C).KeyProtector.recoverypassword > c:\bitlockerkey.txt
PowerTip: View PowerShell Console Host Information
Summary: View Windows PowerShell console host information.
How can I easily find information about the Windows PowerShell console host?
Use the Get-Host cmdlet, and select the RawUI property from the InterhostUserInterface object:
(get-host).ui.RawUI
Redireccionando contenedor default de objetos Computers en AD
Hola a todos!
En esta oportunidad, les quiero dejar como redireccionar el contenedor default donde quedan los objetos Computers al generarse cuando se hace el Join de los equipos a nuestro dominio, como ventaja principal para realizar esta tarea, es cuando queremos desde un principio, aplicar políticas de dominio a nuestros equipos apenas los pongamos en dominio, sin esperar a que los objetos sean movidos de OU después de un tiempo.
En el Contenedor "Computers" donde por default en un dominio que instalamos y no realizamos el cambio, es donde se generan los objetos Computers al realizar el Join de los mismos y donde no podemos adjuntar una GPO de Dominio, con lo cual, muchos optan por correr el comando que les quiero dejar y ahí si, en la nueva OU que direccionamos, podremos poner una GPO de dominio y aplicar configuraciones para que apliquen desde un principio en los equipos que adjuntamos a nuestro dominio.
Como comentario inicial, este comando se corre por dominio, con lo que si tenemos varios dominios donde queremos realizar este cambio, por más que los mismos correspondan a un único Forest, tendremos que correrlo en cada uno de los dominios que deseamos modificar.-
Para empezar, entraremos a nuestra Consola de administración de Usuarios y Computadoras, para lo cual, tenemos que estar trabajando desde un Domain Controller o desde un equipo donde tengamos en Windows Server 2003 o Windows XP las Herramientas Administrativas de Active Directory o en Windows Server 2008 o Superior, el Feature de Administración instalado.
Luego hacemos Start – Administrative Tools – Active Directory Users and Computers como se muestra en la siguiente pantalla:
También podemos abrir la consola, desde Start - Run - Poniendo la llamada a la consola dsa.msc
Donde en la consola, podremos ver el contenedor Default de cualquier implementación de Active Directory donde se generan los objetos "Computer" al realizar el join al dominio, ese contenedor, se llama "Computers":
Ahora para realizar el cambio, generaremos una nueva OU que este directamente desde el raíz del dominio, para lo cual, nos pondremos en el dominio, desplegamos el menu y hacemos New - Organizational Unit como se muestra a continuación:
Donde nos aparecerá una ventana de creación y pondremos el nombre de la OU que deseamos generar, en este caso, pondremos "NewComputers"
Al dar OK, veremos la OU ya generada en la consola de Users and Computers, para también seguir, es importante ir desde la consola, View - Advanced Features:
Ahora desde la nueva OU, desplegaremos el menu, y vamos a "Properties", en la nueva ventana que nos aparece, vamos a la solapa "Attribute Editor" y de la lista de atributos que aparecen, vamos al atributo "distinguishedName", donde daremos la opción "View" y copiaremos la información que tenga dicho atributo.
Una vez realizado el paso anterior, vamos a Start - Command Prompt el cual ejecutaremos como "Administrator" (sobre Command Prompt, desplegamos el menu y seleccionamos la opción "Run as administrator")
En la ventana de CMD que se nos abrirá, escribiremos el comando redircmd, dejamos un espacio y pegamos lo copiado con anterioridad, desplegando el menu y seleccionando la opción "Paste":
Donde se pegará la información del atributo DistinguishedName, quedando la línea de comando completa de la siguiente manera:
Un punto a tener en cuenta, lo que aparece luego de OU= puede variar según la estructura de OUs y Dominio que estemos ejecutando. Luego de que tenemos completa la línea de comando a ejecutar, al dar "ENTER", se realizará el cambio que estamos solicitando y nos dará el aviso que el mismo, se realizó correctamente:
Luego de este cambio, todo equipo Computer que hagamos Join a nuestro dominio, se generará el objeto en la nueva OU que direccionamos.-
Con la herramienta ADExplorer, pueden chequear el atributo de dominio "wellKnownObjects" que tenga aplicado el cambio realizado como se muestra en la siguiente pantalla:
Espero que lo puedan aplicar, que les sea productivo el cambio, ya que como comente al principio, es útil para aplicar GPOs desde un principio en los equipos que son agregados a nuestro dominio de Active Directory.-
Salu2
LeoPonti
Redireccionando contenedor default de objetos Users en AD
Hola a todos!
En esta oportunidad, les quiero dejar como redireccionar el contenedor default donde quedan los objetos Users al generarse cuando desde una aplicación, se generan cuentas y se deja al dominio que las genere en un contenedor por defecto.
En el Contenedor "Users" donde por default en un dominio que instalamos y no realizamos el cambio, es donde se generan los objetos Users.-
Como comentario inicial, este comando se corre por dominio, con lo que si tenemos varios dominios donde queremos realizar este cambio, por más que los mismos correspondan a un único Forest, tendremos que correrlo en cada uno de los dominios que deseamos modificar.-
Para empezar, entraremos a nuestra Consola de administración de Usuarios y Computadoras, para lo cual, tenemos que estar trabajando desde un Domain Controller o desde un equipo donde tengamos en Windows Server 2003 o Windows XP las Herramientas Administrativas de Active Directory o en Windows Server 2008 o Superior, el Feature de Administración instalado.
Luego hacemos Start – Administrative Tools – Active Directory Users and Computers como se muestra en la siguiente pantalla:
También podemos abrir la consola, desde Start - Run - Poniendo la llamada a la consola dsa.msc
Donde en la consola, podremos ver el contenedor Default de cualquier implementación de Active Directory donde se generan los objetos "User", ese contenedor, se llama "Users":
Ahora para realizar el cambio, generaremos una nueva OU que este directamente desde el raíz del dominio, para lo cual, nos pondremos en el dominio, desplegamos el menu y hacemos New - Organizational Unit como se muestra a continuación:
Donde nos aparecerá una ventana de creación y pondremos el nombre de la OU que deseamos generar, en este caso, pondremos "NewUsers"
Al dar OK, veremos la OU ya generada en la consola de Users and Computers, para también seguir, es importante ir desde la consola, View - Advanced Features:
Ahora desde la nueva OU, desplegaremos el menu, y vamos a "Properties", en la nueva ventana que nos aparece, vamos a la solapa "Attribute Editor" y de la lista de atributos que aparecen, vamos al atributo "distinguishedName", donde daremos la opción "View" y copiaremos la información que tenga dicho atributo.
Una vez realizado el paso anterior, vamos a Start - Command Prompt el cual ejecutaremos como "Administrator" (sobre Command Prompt, desplegamos el menu y seleccionamos la opción "Run as administrator")
En la ventana de CMD que se nos abrirá, escribiremos el comando redirusr, dejamos un espacio y pegamos lo copiado con anterioridad, desplegando el menu y seleccionando la opción "Paste":
Donde se pegará la información del atributo DistinguishedName, quedando la línea de comando completa de la siguiente manera:
Un punto a tener en cuenta, lo que aparece luego de OU= puede variar según la estructura de OUs y Dominio que estemos ejecutando. Luego de que tenemos completa la línea de comando a ejecutar, al dar "ENTER", se realizará el cambio que estamos solicitando y nos dará el aviso que el mismo, se realizó correctamente:
Luego de este cambio, todo usuario que se genere desde un aplicativo que tiene delegada al dominio el lugar donde se genere, se creará el objeto en la nueva OU que direccionamos.-
Con la herramienta ADExplorer, pueden chequear el atributo de dominio "wellKnownObjects" que tenga aplicado el cambio realizado como se muestra en la siguiente pantalla:
Espero que lo puedan aplicar y que les sea productivo el cambio según cada una de las estructuras de dominio que administran.-
Salu2
LeoPonti
Revista LatamTechnology #10
Hola a todos!
Les dejo en esta oportunidad, el acceso al nuevo numero de la revista LatamTechnology #10.
Excelente numero con novedades, artículos de interés, entrevistas y mucho mas!!!
URL: https://www.latamtechnology.com/
Saludos!
LeoPonti
Running PowerShell Scripts from a Remote File Share
Summary: Microsoft Scripting Guy, Ed Wilson, talks about running Windows PowerShell scripts from a remote file share.
Microsoft Scripting Guy, Ed Wilson, is here. It is sort of official…
There are at least three Windows PowerShell Saturday events coming up. They are listed on the PowerShell Saturday website. Atlanta and Singapore are already planning (I know, because I will be speaking at both events). The Charlotte event is still early in the planning stages (I will be speaking there also). Of course, don't just take my word for it. Bookmark the PowerShellSaturday website, so you can keep up to date on all the events.
First things first
Note For good background info about running Windows PowerShell scripts from a remote file share, check out the guest blog post written by June Blender and Judith Herman: How to Run PowerShell Scripts from a Shared Directory .
So I have this shared folder on one of my servers. I can open Windows PowerShell and use the Net View command to see all of the shares. I can then use the Get-ChildItem command (dir is an alias) to view the files in the shared folder. This is shown here.
If I want to look at the files in a GUI, I can type the path into Internet Explorer, and view the files in the File Explorer as shown in the following image.
For a background, I happen to know that the remote server is running 32-bit Windows Server 2008. I also found out that the server is running Windows PowerShell 2.0. I did this by using the Invoke-Command cmdlet (icm is an alias) as shown here:
PS C:\> icm -ComputerName dc1 {$PSVersionTable}
Name Value
---- -----
PSRemotingProtocolVersion 2.1
BuildVersion 6.0.6002.18111
PSCompatibleVersions {1.0, 2.0}
PSVersion 2.0
CLRVersion 2.0.50727.4241
WSManStackVersion 2.0
SerializationVersion 1.1.0.1
Open script in ISE
The cool thing is that I can open a Windows PowerShell script in the Windows PowerShell ISE on my 64-bit laptop (running Windows 8a and Windows PowerShell 3.0) from the remote file share. So I do the following:
- I open the Windows PowerShell ISE.
- I click File, then Open.
- In the Open dialog box, I type the UNC path to the remote file share and I press ENTER. I am now viewing the files from the share, as shown in the following image.
I view (and edit if required) the script from the remote file share. When I am ready, I click the green triangle (or press F5) to run the script. At the top of the output pane, I see the UNC location to the script. On the subsequent lines, I see the output.
Keep in mind that the script resides on a remote file share, but the execution of the script takes place on my local computer, and the output that is displayed relates to my local computer. For instance, the remote server is a Dell device, but my local laptop is a Lenovo device. The remote server is named DC1, but my local laptop is named EDLT. The script and the output from the script are shown here.
Run directly in the Windows PowerShell console
But I do not need to open the script in the Windows PowerShell ISE; instead, I can run it directly from the Windows PowerShell console. Two ways to do this are to dot-source the script, or to use the Invocation operator.
PS C:\> . \\dc1\share\ServerNameBios.ps1
PS C:\> & \\dc1\share\ServerNameBios.ps1
The commands and the output from the commands are shown in the following image.
That is all there is to using a Windows PowerShell script from a remote file share. Join me tomorrow when I will talk about more stuff related to running a script from a remote file share.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Script - Export completo de Subnets por Site en nuestro Forest
Hola a todos!
En esta oportunidad, quería dejarles un Script muy interesante, el cual nos permite exportar en pocos segundos, el detalle de las subnets que tenemos en cada uno de nuestros Site del Forest donde necesitemos tener dicho detalle, de estar en una estructura pequeña, no tendrías problemas ni nos demandaría mucho tiempo realizar dicha tarea en forma manual, pero tengan en cuenta ante ambientes muy grandes, que sería de mucho tiempo de trabajo, tener la información exportada en un archivo.
Este detalle nos puede server como inventario o también para realizar un análisis de como tenemos configurado nuestro Site&Services en cuanto a las subnets a que sitio pertenecen, recuerden que tener bien configurado esta parte, hará que las autenticaciones, sean validadas en el sitio local o más cercano de donde está el equipo que el usuario quiere acceder, evitando inconvenientes de lentitud innecesarios.-
Entonces, descargando el archivo *.vbs desde: Link subido a Microsoft TechNet Gallery y guardarlo como list_subnets.vbs y luego, desde línea de comando, nos posicionamos en el directorio donde guardamos el archivo vbs y ejecutamos cscript list_subnets.vbs > export_subnets.txt y en el archivo *.txt que detallamos, nos exportara el detalle de Site y que Subnets están declaradas en el mismo, toda información correspondiente al Forest que pertenece el equipo desde donde corrimos el script.
El archivo export_subnets.txt resultante, tendrá un formato similar a como les detallo a continuación:
Microsoft (R) Windows Script Host Version 5.8 Copyright (C) Microsoft Corporation. All rights reserved.
SITIO1,10.1.10.0/24,10.1.19.0/24,10.1.20.0/24,10.1.27.0/24,10.1.29.0/24,10.1.59.0/24,10.1.60.0/24, 10.1.67.0/24,10.113.33.0/24 SITIO2,10.1.12.0/24,10.1.44.0/24,10.1.6.0/24,10.10.44.0/24,10.11.44.0/24,10.13.44.0/24,10.29.0.0/21, 10.29.4.0/24,10.3.11.0/24,10.3.44.0/24 SITIO3,10.1.22.0/24,10.1.57.0/24,10.1.7.0/24,10.11.7.0/24,10.113.12.0/24,10.113.13.0/24,10.113.27.0/24, 10.113.37.0/24,10.114.12.0/24 SITIO4,10.1.33.0/24,10.1.38.0/24,10.1.4.0/22,10.1.9.0/24,10.10.33.0/24,10.101.0.0/20,10.11.32.0/22, 10.111.1.0/24,10.112.0.0/24 SITIO5,10.1.93.0/24,10.2.93.0/24,10.3.92.0/22,10.4.93.0/24,10.65.93.0/24,10.66.93.0/24,10.67.93.0/24, 10.68.93.0/24,10.69.93.0/24 SITIO6,10.100.42.0/24,10.113.34.0/24,10.113.43.0/24,10.113.44.0/24,10.113.62.0/24 SITIO7,10.100.80.0/24,10.144.144.0/24,10.144.152.0/24,10.144.153.0/24,10.144.38.0/24,10.144.4.0/24, 10.144.8.0/22,10.145.152.0/24
Espero les sea de utilidad.
Salu2
Use PowerShell in Windows 8 to Remove Printers
Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell 3.0 in Windows 8 to remove printers.
Microsoft Scripting Guy, Ed Wilson, is here. The Scripting Wife and I have been talking to various people from the Charlotte Windows PowerShell User Group all week about doing another Windows PowerShell Saturday. It is an awful lot of work, but I think we are going to do this again. The Windows PowerShell Saturday in Charlotte sold out within a few days, and there have been many positive comments about the event. That means that people found it to be a valuable experience. So we will have another Windows PowerShell Saturday. (By the way, if you want to have one where you live, let us know via scripter@microsoft.com.)
To remove a printer with Windows PowerShell, I use the Remove-Printer function from the PrinterManagement module. There are two ways to use the Remove-Printer function:
Remove-Printer [-Name] <String> [-AsJob [<SwitchParameter>]] [-CimSession
<CimSession>] [-ComputerName <String>] [-PassThru [<SwitchParameter>]]
[-ThrottleLimit <Int32>] [-Confirm [<SwitchParameter>]] [-WhatIf
[<SwitchParameter>]] [<CommonParameters>]
Remove-Printer [-AsJob [<SwitchParameter>]] [-CimSession <CimSession>]
[-PassThru [<SwitchParameter>]] [-ThrottleLimit <Int32>] -InputObject
<CimInstance> [-Confirm [<SwitchParameter>]] [-WhatIf [<SwitchParameter>]]
[<CommonParameters>]
What this means is that if I type the exact printer name, I can use the Remove-Printer function directly. It also tells me that I can pipe a printer object to the function. By pipelining a printer object, I can use wildcard characters.
Begin with Get-Printer
I usually begin things by using a Get type of command. So the first thing I do is use the Get-Printer function to see what printers are defined. The command is shown here:
Get-Printer
The command and its associated output are shown here:
I can use a wildcard character to avoid typing a complete printer name as shown here:
PS C:\> Get-Printer | where name -Like "my*"
Name ComputerName Type DriverName
---- ------------ ---- ----------
myotherlaser Local Brother Laser Leg Typ...
Or, I can type the exact printer name and supply it directly to the –Name parameter as shown here:
PS C:\> Get-Printer -Name myotherlaser
Name ComputerName Type DriverName
---- ------------ ---- ----------
myotherlaser Local Brother Laser Leg Typ...
Both of these commands return printer objects, and therefore, they can be piped to the Remove-Printer function. This is shown here:
Get-Printer -Name myotherlaser | Remove-Printer
Get-Printer | where name -like "my*" | Remove-Printer
Remember Whatif
Of course, before I add a Remove-Printer object, I want to use the –Whatif switch to ensure that I am doing exactly what I want to do. Here is an example of a near disaster:
PS C:\> Get-Printer | where name -match "my*" | Remove-Printer -WhatIf
What if: Deleting printer Microsoft XPS Document Writer
What if: Deleting printer \\dc1.iammred.net\HP LaserJet 2100 PCL6
What if: Deleting printer myotherlaser
PS C:\>
Luckily, I used –Whatif, so I did not delete a bunch of my printers.
Directly remove a printer
I can use the Remove-Printer function directly to remove a printer if I know the exact name. If I am unsure of the printer name, I use the Get-Printer function to list my printers, and I copy and paste the name. With quick edit mode turned on, I can highlight the printer name with my mouse, press ENTER to copy it to the clipboard, and then right-click to paste it. This is shown in the image that follows.
Here is the command:
Remove-Printer -Name myotherlaser
After I have deleted the printer, I may decide to delete the printer driver and the printer port (if necessary). To do that, I use the following functions:
PS C:\> Get-PrinterDriver -Name "Brother*"
Name PrinterEnvironment MajorVersion Manufacturer
---- ------------------ ------------ ------------
Brother Laser Leg Type1 Class Dr... Windows x64 4 Brother
PS C:\> Get-PrinterDriver -Name "Brother*" | Remove-PrinterDriver
I use the Get-PrinterPort function, and I decide that I do not need to remove any printer ports.
That is all there is to using Windows PowerShell to remove printers. This also concludes Printer Week. Join me tomorrow when I will talk about running scripts on remote file shares.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Use PowerShell to Change Sign-in Script and Profile Path
Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to modify the sign-in script and profile path in Active Directory.
Hey, Scripting Guy! We are in the middle of an Active Directory migration (primarily moving our client computers from Windows XP to Windows 8). We are also consolidating our file servers and our profile servers. We have multiple sites, and in the past, each site had a one or more domain controllers, multiple file and print servers, and other stuff as needed.
Now, we are collapsing that infrastructure into a single server running Hyper-V. Needless to say, our profiles will be moving to different servers, and we will also be changing our sign-in scripts. So I need an easy way to modify these settings for our users. The new servers will be based on the user's city locations. Can you help?
—RA
Hello RA,
Microsoft Scripting Guy, Ed Wilson, is here. Things have been busy around the Scripting House. I got up early to check the scripter@microsoft.com email and to write a couple of proposals for Windows PowerShell Saturday in Atlanta. According to Mark, I will be making two presentations—one for the beginner track and one for the advanced track. In addition, I have been working on my presentation that I will be conducting remotely for Windows PowerShell Saturday in Singapore.
Find the attribute names
The first thing we need to do is to find the ADSI attribute names for the profile path and for the sign-in script. I open up one of the user profiles and type some bogus information so that I can find the attributes in ADSI Edit. Here is the page from Active Directory Users and Computers:
Now I navigate to the same user object in ADSI Edit and look up the ADSI property names. The names make sense: ProfilePath and ScriptPath. This is shown here:
Now I need to retrieve the information from Active Directory Domain Services (AD DS). I could do all this from inside the Windows PowerShell console, but I decided to use the Windows PowerShell ISE instead. It has better intellisense, and for something like this, it makes things a bit more readable. I decide to use a couple of variables to hold the organizational unit (OU) and the properties that I need to retrieve. I then use Get-ADUser to retrieve the information. Here is this portion of the script:
Import-Module ActiveDirectory
$ou = "OU=Testou,Dc=Iammred,Dc=Net"
$properties = "ProfilePath","ScriptPath", "l"
Get-ADUser -Filter * -SearchBase $ou -Properties $properties
I can highlight only this section of the script to test it. After I see that it works, I pipe the returned information to the Foreach-Object cmdlet. The hardest part of the script is to create the profile path and the script path. I decide to use parameter substitution and the Format operator to do this because, for me anyway, it is easier to read.
I build the profile path based on the city name. I then add Storage1 (which is the name of the storage server) and Profiles (which is the name of the folder that holds the profiles). Next, I use the user's SamAccountName attribute. Here is the string:
$ProfilePath = "{0}\storage1\profiles\{1}" -f $_.l, $_.SamAccountName
Now, to createthe script path. To do that, I again use the city name. I also store the scripts in Storage1, and I place them in a folder named Scripts. The sign-in script is based on the city name and the word LogonScript. Therefore, I am only substituting a single word: the city name, which is the l attribute. Here is the string I use for this:
$ScriptPath = "{0}\storage1\scripts\{0}_logonScript.ps1" -f $_.l
The rest is really easy. All I need to do is to use the Set-ADUser cmdlet to plug in the values. Here is that command:
Set-ADUser $_.samaccountname -ProfilePath $ProfilePath -ScriptPath $ScriptPath
The complete script is shown here:
Import-Module ActiveDirectory
$ou = "OU=Testou,Dc=Iammred,Dc=Net"
$properties = "ProfilePath","ScriptPath", "l"
Get-ADUser -Filter * -SearchBase $ou -Properties $properties |
ForEach-Object {
$ProfilePath = "{0}\storage1\profiles\{1}" -f $_.l, $_.SamAccountName
$ScriptPath = "{0}\storage1\scripts\{0}_logonScript.ps1" -f $_.l
Set-ADUser $_.samaccountname -ProfilePath $ProfilePath -ScriptPath $ScriptPath
}
When I run the script, nothing returns. But that is what I want (I really do not want a whole bunch of errors). Here is the ISE and the blank output from running the script:
I check Active Directory Users and computers to ensure that everything worked as planned. It is fine, as shown here:
RA, that is all there is to using Windows PowerShell to create values for the sign-in script and the profile path. Active Directory Week will continue tomorrow when I will talk about logging an attribute change.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Use PowerShell to Create New Printer Ports
Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell 3.0 to create new printer ports in Windows 8.
Microsoft Scripting Guy, Ed Wilson, is here. One of the exciting things that is happening around the Scripting House is the appearance of new Windows PowerShell Saturday events. We have new events coming up in Atlanta, Singapore, and Charlotte. For information about these and other events, check out my site, Scripting Community. If you do not know what Windows PowerShell is, check out my blog post, Community: All about PowerShell Saturday .
To programmatically create a working printer, there are at least three steps:
- Create the printer port.
- Install the printer driver.
- Install the printer (by using the printer port and the printer driver).
Today I am talking about creating the printer port.
Using PowerShell to work with printer ports
Before I create anything, I like to know what I have going on with my computer. I can use the Get-PrinterPort function to list existing printer ports on my local computer:
Get-PrinterPort
I can also use this function to retrieve printer port information from a remote server running Windows Server 2008 and Windows PowerShell 3.0 as shown here:
Get-PrinterPort -ComputerName dc1
The commands and the output from the commands are shown in the following image.
Adding a new printer port
To add a new printer port, I use the Add-PrinterPort function in Windows 8 or Windows Server 2012. By using the Add-PrinterPort function, I can add a local printer port, a TCP printer port, or an LPR printer port.
Most of the time, if I am creating a local printer port, I want to print directly to a printer on the network. Doing this bypasses a print server. Therefore, in the case of large print jobs, I lose flexibility because my laptop must remain on to manage the large print job. But for short documents, it is fast. Also by printing directly to the printer, I can configure things the way that I want.
By using Windows PowerShell, it is easy to create a TCP printer port. I use the Add-PrinterPort function, create a name for the port (the name does not matter, but it is best to use something that makes sense in the printing context). The IP address of the printer itself becomes the value for the PrinterHostAddress parameter. Here is the command I used:
Add-PrinterPort -Name 'HP_Direct:' -PrinterHostAddress '192.168.1.88'
I do not need to specify a value for the port number unless the printer is configured to use a different value than the default. The Add-PrinterPort function has four parameter sets, and I use the third one to create a TCP printer port. Here are the optional parameters for this parameter set:
Add-PrinterPort [-Name] <String> [-PrinterHostAddress] <String> [-AsJob
[<SwitchParameter>]] [-CimSession <CimSession>] [-ComputerName <String>]
[-PortNumber <UInt32>] [-SNMP <UInt32>] [-SNMPCommunity <String>]
[-ThrottleLimit <Int32>] [-Confirm [<SwitchParameter>]] [-WhatIf
[<SwitchParameter>]] [<CommonParameters>]
I have SNMP turned off on my network, so I do not need to specify a community string or any of that stuff.
When I add a printer port, I do not need an elevated Windows PowerShell console. In Windows 8, I can do this without additional rights. In addition, Windows PowerShell does not make any checks. Therefore, if the IP address is wrong or inaccessible, no warnings generate. This is shown here:
Add-PrinterPort -Name 'bogus:' -PrinterHostAddress '10.10.10.10'
The command and the output from Get-PrinterPort are shown in the following image.
Deleting the printer port
When I create something via Windows PowerShell, I also always like to know how to clean it up. To delete a printer port, I use the Remove-PrinterPort function. The use of the Remove-PrinterPort function is shown here:
Get-PrinterPort | Where name -eq 'bogus:' | Remove-PrinterPort
The following image shows the command and its associated output.
That is all there is to using Windows PowerShell to create new printer ports. Printer Week will continue tomorrow when I will talk about installing printer drivers.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Use PowerShell to Customize Server Manager
Summary: Guest blogger, Rolf Masuch, talks about using Windows PowerShell to customize Server Manager.
Microsoft Scripting Guy, Ed Wilson, is here. Today we have a guest post written by Rolf Masuch, who is a senior consultant for Microsoft in Germany. Today is Rolf's birthday, and he wanted to start the celebration off right by sharing a couple of cool scripts with us. Take it away Rolf…
When it comes to the new versions of Windows Server 2012 R2 and Windows Server 2012, one of my most-loved changes is to Server Manager. The new Server Manager Dashboard looks like this:
Lots of documents have been written already about this new way of working. Today I'd like to share two extension scripts that I thought would be helpful for the community because when it comes to automating Server Manager, you cannot do two things:
- Add servers to your list of managed servers
- Create groups that contain a custom list of servers
You will find the respective menu entries in Server Manager when you click Manage.
But first, let's look behind the curtain of Server Manager. It stores information in an XML file that is saved per user at this location:
$ENV:APPDATA\Microsoft\Windows\ServerManager\ServerList.xml
Additionally, it is useful to know that every time you close a running Server Manager instance, it can overwrite your scripted changes. We want to take care that before we make changes to the XML file, we close the Server Manager process. We also need to make all changes in an elevated process.
When it comes down to writing additional entries to the file, you may think, "Hey, it is just XML, this is easy." But when you look at the structure of the XML file, you see that this is not so simple. The following example is from a freshly installed system with one additional group:
ServerManager.xml
***
<?xml version="1.0" encoding="utf-8"?>
<ServerList xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" localhostName="MyCloudComp001" xmlns="urn:serverpool-schema">
<ServerInfo name="MyCloudComp001" status="1" lastUpdateTime="2013-08-08T09:01:26.7659233+00:00" locale="en-US" /><ServerGroupInfo id="3" name="MyGroup" />
<ServerGroupMembership server="MyCloudComp001" serverGroupId="3" />
</ServerList>
***
As you see from the initial lines, the XML structure is using an additional namespace that is named urn:serverpool-schema. When you want to add new elements to this structure, you need to take care of that. So how is it done?
Let's look at the script Add-ServerToManagedServerList.ps1. Here are the essential lines:
$NewServer = $ServerList.CreateElement("ServerInfo")
$NewServer.SetAttribute("name",$ComputerName.ToString()) | Out-Null
$NewServer.SetAttribute("xmlns","urn:serverpool-schema") | Out-Null
$ServerList.ServerList.AppendChild($NewServer) | Out-Null
So setting the right attribute in the right notation does the trick for us. Now I have the newly added server in Server Manager.
The same is true when it comes to adding the server to an existing group.
$NewServerInGroup = $ServerList.CreateElement("ServerGroupMembership")
$NewServerInGroup.SetAttribute("server",$ComputerName.ToString()) | Out-Null
$NewServerInGroup.SetAttribute("serverGroupId",$PSItem.Id) | Out-Null
$NewServerInGroup.SetAttribute("xmlns","urn:serverpool-schema") | Out-Null
$ServerList.ServerList.AppendChild($NewServerInGroup) | Out-Null
Because this is an existing group, we have to make sure that the group's ID is added to the attributes of the entry. So this is how you add a new server to your list of managed servers. Simple, isn't it? A new server group is shown here:
You may also want to add some custom groups. The added script, New-ServerManagerGroup.ps1, helps you take care of that. It creates a random number and uses it as the needed group ID.
$Global:ServerGroupID = Get-Random -Maximum 1000
$NewServerGroup = $ServerList.CreateElement("ServerGroupInfo")
$NewServerGroup.SetAttribute("id",$Global:ServerGroupID) | Out-Null
$NewServerGroup.SetAttribute("name",$Name) | Out-Null
$NewServerGroup.SetAttribute("xmlns","urn:serverpool-schema") | Out-Null
$ServerList.ServerList.AppendChild($NewServerGroup) | Out-Null
I've added additional switches, such as –Backup (to save the previous ServerManager.xml) and –StartServerManager (for launching Server Manager after your additions). Be aware that the provided scripts always check for a servermanager.exe process and end this process silently for you.
I hope these little scripts help the community, and I'm looking forward to your comments.
The following scripts are uploaded on the Script Center Repository:
~Rolf
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Use PowerShell to Log Changes to AD DS Attributes
Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to log changes made to Active Directory Domain Services attribute values.
Hey, Scripting Guy! We are in the process of merging a couple of resource domains, and we need to modify some user accounts prior to the move. I have been tasked with making the changes, and I plan to use Windows PowerShell to perform the actual work. I need to create before and after logs. The before log shows the value of the attributes that I am going to change prior to running the script, and the after log will show the value of the attributes after running the script. Can you show me how I might go about doing this? Thanks, Scripting Guy, you are the best!
—CX
Hello CX,
Microsoft Scripting Guy, Ed Wilson, is here. This morning I am sitting on the lanai, and sipping a cup of English Breakfast tea. I put a bit of lemon grass, hibiscus flower, rose hips, spearmint, and a cinnamon stick in the tea. The flowers give it a citrus flavor, and the mint makes it very refreshing. The trick is that I only let it steep for three minutes, and that keeps it from becoming too bitter. It took me several tries to get this one just right. Because it is pretty early, it is not too hot or humid outside yet. I have my Surface RT, and am checking my scripter@microsoft.com email.
So, CX, you did not specify how you want your logging to take place, but I decided that exporting to a CSV file would work out well. Then you could import it into Microsoft Excel if you want to do so.
Finding the attribute and values
The first thing to do is to create a little script that will populate an attribute with before values. I am going to populate the Post Office Box attribute, so I need to look it up in ADSI edit. I come up with the following (surprisingly, it is named postOfficeBox):
I write a little script to add values to this attribute. Here is the script:
Import-Module activeDirectory
$ou = "ou=testou,dc=iammred,dc=net"
$i = 1
Get-ADUser -Filter * -SearchBase $ou |
ForEach-Object {
Set-ADUser $_ -POBox "Post Office Box $i"
$i++ }
Now I want to see how many different cities are represented by the users in the organizational unit (OU). I modify my script a bit and use the –Unique parameter from the Select-Object command. This is shown here:
Get-ADUser -Filter * -SearchBase $ou -properties $properties | select l -Unique
The following output tells me that I have three cities:
Atlanta
Charlotte
Jacksonville
Therefore, I need to add a bit of logic to detect the city. If the city is Atlanta, I will set the postOfficeBox attribute to 222; if it is Charlotte, I will set it to 333; and if it is Jacksonville, I will set it to 444.
Making the changes
The first thing I do is use the Get-ADUser cmdlet to return the user name and the postOfficeBox attribute. I use the Select-Object cmdlet to get these two attributes, and I pipe the output to Export-CSV. No problem…until I open the spreadsheet in Excel. Here is the results:
The issue is that for some reason, the postOfficeBox attribute is a collection. I therefore modify my script a bit, and I select the first PO Box. Here is the script:
Import-Module activeDirectory
$ou = "ou=testou,dc=iammred,dc=net"
$Before = "c:\fso\before.csv"
$properties = "PostOfficeBox"
Get-ADUser -Filter * -SearchBase $ou -properties $properties |
Select name, @{L='pobox';E={$_.postofficebox[0]}} |
Export-Csv -Path $before -NoTypeInformation -Force
Now I open the script in Excel, and it appears like I expected:
So now I use the Get-ADUser cmdlet to retrieve my user objects. I pipe everything to a Foreach-Object cmdlet, and I use a Switch statement inside the Foreach-Object. I read a Switch statement like a series of If statements, for example: If the city matches Atlanta, then I set the POBox variable to 222.
I then use the Set-ADUser cmdlet inside the Foreach-Object cmdlet to make the actual changes. Here is the script:
Import-Module activeDirectory
$ou = "ou=testou,dc=iammred,dc=net"
$properties = "l","PostOfficeBox"
Get-ADUser -Filter * -SearchBase $ou -properties $properties |
ForEach-Object {
Switch ($_.l)
{ "Atlanta" {$pobox = "POBox 222"}
"Charlotte" {$pobox = "POBox 333"}
"Jacksonville" {$pobox = "POBox 444"} }
Set-ADUser $_ -POBox $pobox
}
Now I run my documentation script again and open the Excel spreadsheet. I can see that the changes took place as expected. Cool.
CX, that is all there is to using Windows PowerShell to make changes to AD DS attribute values and to log the changes. Active Directory Week will continue tomorrow when I will talk about different ways of working with Active Directory.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Version de Schema en nuestro Forest
Hola a todos!
En esta oportunidad, quiero dejarles las formas en las que podemos chequear la versión de nuestro Schema de Active Directory, esto identificará la versión de Sistema Operativo de nuestros Domain Controllers, no en general, ya que con eso lo identificamos viendo el Functional Level de nuestra estructura, pero si sabremos que al menos un Domain Controller de nuestra infraestructura, es de la versión de nuestro Schema, ya que para promover un Domain Controller con una versión de Sistema Operativo superior, si o si tenemos que realizar un upgrade o extender nuestro Schema del Forest.-
Las versiones de Schema hasta el momento y a que versión de Sistema Operativo corresponden, son las siguiente:
* 13 - Windows 2000 Server
* 30 - Windows Server 2003
* 31 - Windows Server 2003 R2
* 44 - Windows Server 2008
* 47 - Windows Server 2008 R2
* 51 - Windows Server 8 Developers Preview
* 52 – Windows Server 8 Beta (Disponible al público)
* 56 - Windows Server 2012
Si bien tenemos scripts y otras herramientas para chequear la versión de nuestro Schema, a mi en este post me gustaría identificar cuatro formas:
1) Mediante dsquery.
2) Mediante consola de adsiedit.
3) Mediante consola de ldp.
4) Mediante clave de registro (regedit).
1) Mediante dsquery:
Desde un Domain Controller o equipo perteneciente al dominio, teniendo las herramientas administrativas o el features de administración de Active Directory, ejecutaremos la línea de comando mediante un CMD.
En donde ejecutaremos la siguiente linea de comando:
dsquery * cn=schema,cn=configuration,dc=leoponti,dc=net -scope base -attr objectVersion
Donde "dc=leoponti,dc=net" corresponde a las referencias del Forest que tengan cada uno de ustedes, en mi caso el laboratorio aplica a un distinguishedname "dc=leoponti,dc=net"
Al ejecutarlo, nos dara la versión que tengamos en cada una de las estructuras según se muestra a continuación:
2) Mediante consola de adsiedit.
Desde un Domain Controller o equipo perteneciente al dominio, teniendo las herramientas administrativas o el features de administración de Active Directory, ejecutaremos dentro de las herramientas administrativas, la consola ADSIEdit:
En la parte superior izquierda de la consola que se nos abrirá, en la opcion ADSI Edit, desplegamos el menu y seleccionamos "Connect to", donde nos aparecera una ventana de selección y pondremos las referencias de Schema como se muestran a continuación:
Una vez que nos conecta, desplegamos el menu dentro del CN=Schema y seleccionamos properties:
En la ventana que nos aparecerá, buscamos la opción que dice "objectVersion" como se muestra a continuación:
3) Mediante consola de ldp.
Desde un Domain Controller o equipo perteneciente al dominio, teniendo las herramientas administrativas o el features de administración de Active Directory, vamos a "Run"
Ejecutamos la herramienta ldp y dentro de la misma, vamos a Connection - Connect..
Donde nos aparecera una ventana para configurar la conexión que deseamos realizar y cargamos en "Server:" el FQDN del dominio o la IP/hostname de un Domain Controller.
Luego que nos conectamos al dominio, necesitamos autenticarnos para poder ver la información del mismo, donde hacemos en la misma consola: Connection - Bind:
Donde nos aparecerá una ventana para cargar credenciales validas del dominio al que nos queremos conectar, si ya estamos logeados con credenciales del dominio a consultar, damos OK sin cargar ninguna referencia:
Podremos chequear entonces, que estamos conectados con credenciales válidas:
Luego, para que nos aparezca la estructura que deseamos consultar, vamos a View - Tree como se muestra a continuación:
Donde nos aparecerá una ventana para cargar la ruta completa de nuestra estructura a consultar desde LDP, en nuestro caso, seleccionaremos el distinguishedname correspondientes a nuestro Schema, como se muestra a continuación:
En el arbol del lado izquierdo, podremos dar doble click y nos aparecerá del lado derecho, en todas las referencias, una linea con "objectVersion:" y la información que estamos buscando:
4) Mediante clave de registro (regedit) .
Desde un Domain Controller o equipo perteneciente al dominio, teniendo las herramientas administrativas o el features de administración de Active Directory, vamos a "Run"
En la línea de comando, ejecutaremos la consola "regedit".
En la rama de registro, buscamos: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\NTDS\Parameters y ahi dentro, la clave: "Schema Version" donde nos aparecerá el valor que estamos buscando:
De esta forma, les dejo cuatro maneras de poder buscar y tener el valor de que versión esta nuestro Schema de Active Directory.-
Espero que les sea de utilidad.
Salu2
LeoPonti.
Weekend Scripter: Run PowerShell Scripts from Remote File Share: Part 2
Weekend Scripter: Run PowerShell Scripts from Remote File Share: Part 2
Summary: Microsoft Scripting Guy, Ed Wilson, continues his discussion about running scripts on a remote file share.
Microsoft Scripting Guy, Ed Wilson, is here. This week has been absolutely bizarre. I have been really busy working with a select group of Honorary Scripting Guys for upcoming blog posts. I must say, there is some absolutely way cool, knock-out stuff in the works. But of course, to make all of this streamlined, I had to set up a shared Office 365 SharePoint site, grant permissions, create views, test things out, and all of that. You know what? Dude, it was easy!!! As you may guess from the three exclamation points, I was surprised. I must say that I was dreading it. I will also say that it was so intuitive that I did not once have to use Help or search for How-To articles. It really makes sense, and it has actually been a fun project. As one twentieth-century philosopher said, "I love it when a plan comes together."
Examining script execution policy
Note This is the second in a multipart series of posts. The first post was Running Scripts from a Remote File Share.For good background info about running Windows PowerShell scripts from a remote file share, check out the guest blog post written by June Blender and Judith Herman: How to Run PowerShell Scripts from a Shared Directory .
By default when you open Windows PowerShell, the execution of scripts is disabled. This is because the default script execution policy in Windows PowerShell is restricted. To see the current script execution policy, use the Get-ExecutionPolicy cmdlet. For the current user, all you need to do is type the cmdlet name. This is shown here:
PS C:\> Get-ExecutionPolicy
RemoteSigned
To see all of the execution policies, use the –List switch as shown here:
PS C:\> Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine Unrestricted
You can see that there are multiple levels to which the script execution policy can be set. An ordinary user can change the CurrentUser script execution policy (unless it is specified via Group Policy. In that case, it cannot be modified by a local user). When the execution policy is first checked, it is restricted; therefore, no scripts will run. In the following example, the execution policy is set to RemoteSigned for the current user, and a check verifies that the change works.
What is RemoteSigned, anyway?
A good setting to use in an enterprise situation is RemoteSigned. This means that a script from a remote location must be signed by a recognized Certification Authority (CA) with a code-signing certificate. There are specific trusted roots that are set up automatically. I can see them by using the Cert PS: drive and looking at CurrentUser\Root. The command is shown here:
dir Cert:\CurrentUser\Root
The following image shows the command and output from the command.
So, if a script runs from a remote location, it must be signed by one of the CAs with a root listed in the previous output. I can use Group Policy to add a trusted CA, so I can issue code-signing certificates on my local network. I can also purchase a code-signing certificate from the Internet and if it is trusted, everything will be groovy. But I only need to do that if the location is remote.
Note Refer to the post listed earlier by Judith and by June for more information about this.
Because Windows PowerShell relies on the Internet Explorer definition of what is remote, a network share on my home domain is considered remote. Therefore, it needs to be signed. But more than that, even if I set my execution policy to Unrestricted, it STILL will prompt prior to running. This is by design, but it can be annoying. The best way to modify the Internet Explorer trusted sites setting is to use Group Policy. This is shown here:
In my mind, the best way to do this via Group Policy is to create a special Group Policy Object (GPO) with this setting and then apply it to appropriate scope within the domain. Give it a nice name so it makes it easy to keep up with.
After I have made my changes—even with RemoteSigned as the execution policy—I can run my scripts from network shares. This is because the network shares are not considered remote. This is shown here.
Well, that is about it for today. I am going to head out to my woodworking shop and work on my hand-cut dovetails. Join me tomorrow when I will continue this discussion about remotely running scripts from file shares.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Weekend Scripter: Run PowerShell Scripts from Remote File Share: Part 3
Summary: Microsoft Scripting Guy, Ed Wilson, continues his discussion about running scripts from a remote file share.
Microsoft Scripting Guy, Ed Wilson, is here. Some things should just be easier. For example, I should have access to client-side cmdlets to work with SharePoint. Many times, as a user, I need to accomplish repetitive tasks, and a few cmdlets could really come in handy. Running scripts from remote file shares should be easier as well.
Easier? What am I talking about? Well when someone asks a question, there are so many "it depends," "maybe," and "whatever" stuff going on that it really makes what should be easy very complicated. For example, in a freshly created Windows Server 2012 forest, I created a share on the domain controller. I modified the script execution policy on the client, and I could run scripts from the share just fine. No configuration, no signing, no nothing. It just worked. But to make a proclamation would take hours of testing in all different sorts of variables.
The easy way to run a script
Note This is the third in a multipart series of posts. The first post was Running Scripts from a Remote File Share.The second post was Weekend Scripter: Run PowerShell Scripts from Remote File Share: Part 2. For good background info about running Windows PowerShell scripts from a remote file share, check out the guest blog post written by June Blender and Judith Herman: How to Run PowerShell Scripts from a Shared Directory .
The easy way to run a script from a remote file share is to use the Bypassmethodology. This is not a security hole, because the script execution policy and the associated settings are not really security features—they are a security convenience. This means that they are in place to remind me to do the right thing—to encourage me to follow best practices. But they are not put in place to discourage getting the job done.
So, all the discussion about the script execution policy and signed scripts can be bypassed if I need to do so. What is a common requirement? Well, running a script from a scheduled task, or from within a Group Policy Object. If the desktop and network configuration are complicated to the point of not knowing what will go on, I can use Bypassmodeand still get my scripts to run.
To illustrate this point, I change my script execution policy to Restricted. This is the way it comes out of the box. Scripts do not run.
Using Bypass mode
So, if I want to run a script in Bypass mode, I can use the Run dialog box. One problem I have with the Run dialog box is that it is very small, and it does not resize. The Run box is shown here:
So, what I like to do is open Notepad, compose my command, and then paste it into the run dialog box. There are a couple of things that are important to the command. First, I add –NoExit. From a scheduled task, I would not do this. I would, instead, have my script output to a log file. I added –NoExit so that I could see the output. The key to making this work is specifying the –ExecutionPolicy parameter of Bypass. I then provide the UNC path to the script that I want to run. I would use this exact sort of syntax (without the NoExit) to run a script from a scheduled task. Here is my command:
powershell -noexit -executionpolicy bypass -file \\dc1\Share\ServerNameBios.ps1
Here is the command in Notepad:
When the command runs, it opens a new instance of Windows PowerShell, executes the script, and displays the output from the script. The execution policy of the newly created instance of Windows PowerShell is Bypass. This is shown in the following image.
Well, that is it for today. I am heading outside, so have a great day, and join me tomorrow as I begin Active Directory Domain Services Migration Week.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Weekend Scripter: Understanding PowerShell in Windows 7
Summary: Microsoft Scripting Guy, Ed Wilson, talks about understanding Windows PowerShell in Windows 7.
Microsoft Scripting Guy, Ed Wilson, is here. This morning I am sipping a cup of English Breakfast tea, with goji berries, lemon grass, and cinnamon. The taste is quite nice, and because the goji berries are sweet, I do not need to add any sugar or honey to my tea. Goji berries are not indigenous to Charlotte, North Carolina, so I use dried berries that I order with my other herbs and spices. Along with my tea, I am eating some homemade scones that the Scripting Wife made with the goji berries. They are rather lovely.
One of the more common questions I get about Windows PowerShell 3.0 runs something like this,"I have Windows PowerShell 3.0, but I do not see the Get-Disk cmdlet." (Or words to that effect.) Part of the confusion stems from confusing Windows PowerShell 3.0 with the operating system.
Note For information about installation, refer to Install PowerShell 3.0 on Windows 7.
For example, in Windows 7, when I install Windows PowerShell 3.0, I have access to 355 cmdlets and functions. To find this information, I first imported all of the modules, and then I used the Get-Command cmdlet to retrieve all functions and cmdlets. This is shown here:
In Windows 8, I do not need to install Windows PowerShell 3.0 because it is part of the operating system. When I import all of the modules and count the number of cmdlets and functions in Windows 8, I come up with 988. The output is shown in the following image.
Note Interestingly enough, the output from $PSVersionTable is a little different in Windows 7 and Windows 8.
Look at the modules
So, where does the difference between Windows PowerShell 3.0 in Windows 7 and In Windows 8 come from? Well, it comes from the modules. In Windows 8, many of the teams at Microsoft created modules to permit remote management of aspects of their configuration. In many cases, this took the form of wrapping various WMI classes that have been part of the operating system for a long time. Therefore, just because I am working in Windows 7, it does not mean that I am unable to use Windows PowerShell to manage it—but it will be a bit more difficult.
So what are the modules that are available in Windows 7 after I install Windows PowerShell 3.0? They are listed here:
PS C:\> Get-Module -list | select name
Name
----
AppLocker
BitsTransfer
CimCmdlets
ISE
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Microsoft.PowerShell.Security
Microsoft.PowerShell.Utility
Microsoft.WSMan.Management
PSDiagnostics
PSScheduledJob
PSWorkflow
PSWorkflowUtility
TroubleshootingPack
To get an idea of the number of cmdlets in each module, I decide to create a custom property in the Select-Object cmdlet. Here is the command that I created (this is a single-line command that I broke into multiple lines for easier reading):
Get-Module -list | select name,
@{L='commands';E={(Get-command -commandtype Function, Cmdlet -module $_.name).count}} |
sort commands -Descending| ft –auto
The command and its associated output are shown in the following image:
By examining the modules and the cmdlets, I can see where the Windows PowerShell 3.0 cmdlets and functions reside, and determine from whence they actually come.
Join me tomorrow when I will examine Windows PowerShell 3.0 in Windows 8.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Weekend Scripter: Understanding PowerShell in Windows 8
Summary: Microsoft Scripting Guy, Ed Wilson, talks about understanding Windows PowerShell 3.0 in Windows 8.
Microsoft Scripting Guy, Ed Wilson, is here. It is an exciting and great day! I have been working a bit to solidify the editorial calendar for the Hey, Scripting Guy! Blog. I can say that there are some absolutely awesome posts coming up in the next couple months. I am not just saying this because I am writing them. Nope. I have a great lineup of guest writers. The upcoming stuff will simply rock!
Windows 8 posh stuff…
One of the really great things about Windows 8 is the implementation of Windows PowerShell 3.0. But many of the really cool commands (cmdlets or functions) are not strictly Windows PowerShell 3.0. For example, one function I use on a regular basis when I am traveling is Get-NetAdapter. This command tells me if a network adapter is up. Because I toggle my wireless and my Ethernet adapter connections (on or off depending on the network), I often need to see if a particular adapter is up.
Another function I use a lot when I am traveling is the Get-NetConnectionProfile function. This tells me how a particular network adapter has been identified by the operating system. I can modify the profile by using Set-NetConnectionProfile. I need to use this a lot when I am traveling and I want to demonstrate Windows PowerShell.
Neither of the two previously mentioned functions are part of Windows PowerShell 3.0, per se. They are included in modules that ship with Windows 8. The associated modules are shown here:
PS C:\> Get-Command Get-NetConnectionProfile, Get-NetAdapter
CommandType Name ModuleName
----------- ---- ----------
Function Get-NetConnectionProfile NetConnection
Function Get-NetAdapter NetAdapter
Am I being pedantic? If so, it is not my intention. It is important to know where specific functionality arises, so that when I install Windows PowerShell 3.0 onto a computer running Windows 7, I will know what to expect. This concept will be important when Windows 8.1 ships with Windows PowerShell 4.0 because Windows PowerShell 4.0 in Windows 8.1 will expose certain cmdlets and functions that may not be available if I install Windows PowerShell 4.0 on a down-level system.
Emulating capability
With all the great commands in Windows 8, it is easy to forget that the capability comes from modules that ship with the operating system, and that they are not part of Windows PowerShell 3.0 core installation. But it is Windows PowerShell 3.0 that makes these cool modules shine. Most of the capability comes from the CIM infrastructure that is part of the Windows Management Framework 3.0 (where you obtain Windows PowerShell 3.0).
For example, the Get-NetAdapter function uses CIM to expose network adapter information. It is very convenient. The command and its associated output are shown here:
I can achieve the same output in Windows 7 by using Windows PowerShell 3.0. I use the Get-CimInstance cmdlet, query the Win32_NetworkAdapter WMI class, and choose the appropriate properties. The command is a bit longer than just typing Get-NetAdapter, but if I use it all the time, all I need to do is write my own function. Following is the command (gcim is the alias for Get-CimInstance, Select is the alias for Select-Object, and ft is the alias for Format-Table). This command is a single-line command that I broke at the pipe character for readability.
gcim win32_networkadapter |
select netconnectionid, description, interfaceindex, macaddress, speed |
ft * -auto
Here is the command and the output from the command:
Join me tomorrow as I begin a series of posts called Windows PowerShell Workflow for Mere Mortals. It is a great series, and you will not want to miss it.
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. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
Windows Server 2012 - Generando Disco USB Booteable
Hola a todos!
En esta oportunidad, quiero compartir con ustedes una forma sencilla de hacer un dispositivo USB booteable con Windows Server 2012, de esta misma forma, también se puede hacer con Windows Server 2008R2, Windows 7 y Windows 8.-
Para comenzar, tenemos que descargar la Herramienta Windows 7 USB/DVD Tool desde Microsoft Store Online: https://www.microsoftstore.com/store/msstore/html/pbPage.Help_Win7_usbdvd_dwnTool
Una vez que se descarga el instalador, corremos la instalación del mismo, para lo cual, tenemos que tener instalado previamente .NET Framework 3.5, si no lo tenemos instalado, nos aparecerá un aviso de descargo e instalarlo como se muestra a continuación:
Donde vamos a "Download and install this feature" para procederá la instalación de .NET Framework 3.5
Cuando finalice la instalación de .NET Framework, nos aparecerá el aviso como se muestra a continuación:
Al darle "Close", si comenzaremos la instalación de la Tool que necesitamos para poder realizar el dispositivo USB Booteable:
Aceptando la pantalla de bienvenida, daremos la opcion "Next":
Al dar la opcion "Install", comenzará el proceso de instalación.
Dando Finish, se cerrará la instalacion habiendo finalizado la misma.
Ahora ejecutaremos la Tool desde el icono que nos apareció en el escritorio.
Donde nos aparecerá la siguiente ventana dando comienzo al wizard para generar el dispositivo booteable.
Donde iremos a "Browse" y seleccionamos la ISO de Windows Server 2012 que previamente hayamos descargado desde la Web de Microsoft y tengamos localmente en nuestro disco.
Daremos NEXT y nos apareceran las siguientes posibilidades.
Start over: Volveremos a la pantalla para cargar en la Tool, la imagen ISO de nuestro Sistema Operativo Windows Server 2012.
USB Device: Seguiremos la Tool para generar el disco booteable con un dispositivo USB.
DVD: Seguiremos la Tool para generar el disco booteable con nuestra unidad de DVD.
En nuestro caso, seleccionaremos la opción USB device para seguir nuestro wizard.
Luego de confirmar la unidad con el dispositivo USB, daremos "Begin copying" para comenzar el proceso de dar format al dispositivo y posterior copia en el dispositivo y configurarlo como booteable.
Luego de dar el formato, comienza la copia de archivos:
Una vez que finalice correctamente, nos aparecerá la confirmación como se muestra a continuación:
De esta forma, tendremos nuestro dispositivo USB con particularidad de ser booteable y listo para poderlo utilizar en donde querramos instalarlo.
Espero que les sea de utilidad y lo puedan aplicar, nunca esta de mas tener preparada esta forma de instalar nuestros Servidores, ya que en mas de una oportunidad, es la única manera que tenemos de instalarlos.-
Salu2
LeoPonti
Enable Task Synchronization in SharePoint Online 2013 and Exchange Online 2013
As preparations for my session in the SharePoint Ignite course, I wanted to do a demo of the new task synchronization in SharePoint 2013 without installing Exchange and configuring the Server-to-Server (S2S) authentication. So, I thought that Office 365 vNext would be the perfect environment for me. I have created a task in SharePoint and went to Outlook Web Access to see if my SharePoint tasks are already there, and … nope. Again, tried to create a task in Outlook and return to my tasks list in SharePoint and no tasks from Outlook. After one hour of investigation, I clicked on the ribbon menu and saw the "Sync to Outlook" button and asked myself "What is the chance that this function will be the trick in here? Much to my surprise, it was it! This button is actually the trigger to enable the synchronization of tasks between SharePoint and Exchange.
From the Ribbon menu, click on "Sync to Outlook" button.
In the "Sync Tasks with Microsoft Outlook" modal dialog window, check the "Sync tasks" option.
Now your Outlook account will include both Exchange and SharePoint tasks in the same view.
All that's left to do is to perform the tasks
How to enable promoted links in publishing portal site
In SharePoint 2013 each team site by default comes with a new feature named Promoted Links list pre-loaded with links to commonly performed actions. These links are displayed as Tiles in the home page.
However, in Publishing Portal template you won't find it unless you activate a feature named "Team Collaboration Lists".
To enable the "Promoted Links" list, please follow the below steps:
- In your Publishing Portal site, click on Settings icon.
- Under site actions category, click on Site Features.
- Look for Team Collaboration Lists feature and active it by clicking on Activate button.
- Click on Settings icon and then press on Add an App button.
- Search for Promoted Links and add this app to your site in order to create your own list.
Popular posts from this blog
Windows Azure:新计划程序服务,读取访问同步冗余存储以及监测更新 [原文发表地址] Windows Azure: New Scheduler Service, Read-Access Geo Redundant Storage, and Monitoring Updates [原文发表时间] December 12, 2013 12:41 PM 今天早上我们推出了windows Azure的另一组增强功能。今天的新功能包括: 程序调度:新的windows Azure计划程序服务 存储:新的同步读写冗余存储方案 监测:windows Azure服务的监测及诊断的增强功能 所有的这些改进现在都可以使用(注意有些功能仍然是在预览)。下面是有关他们的更多详细信息: 程序调度:新的windows Azure计划程序服务 我很高兴宣布我们可以预览新的Windows Azure调度服务。Windows Azure调度服务允许你安排启用HTTP/S端点的任务或者按你制定的任何计划向存储队列上发送信息。使用调度程序,你可以创建可靠的调用Windows Azure内部或外部服务的任务并且按照常规计划立刻运行或者设置他们在未来某刻运行。 想要开始使用调度程序,首先你需要在 Windows Azure Preview 页面上为预览进行注册。一旦在预览页中注册成功后,你可以登陆到管理门户并且开始使用它。 创建一个调度任务 一旦你在你的订阅中启用调度预览,你可以用以下几个简短步骤很容易的创建一个新的任务。 在Windows Azure门户管理网站内单击 新建-> 服务程序 -> 调度 –> 自定义创建: 选择一个你想要运行任务的Windows Azure 区域,之后选择一个已有的任务收集器或者创建一个新的并把任务加进去: 之后你就能定义你的任务操作。在本例中,我们会创建一个向web站点发送GET 请求的HTTP 操作(你也可以使用其他的HTTP协议,像HTTPS)。 对于处理长时间的请求或者在脱机状态启用某项服务,你也许更期望给存储队列添加一些信息而不是坚持启用一个Web 服务。要给存储队列添加信息你只需要选择存储队列作为你的操作,之后创建或选择一个存储帐号及队列用来发送请求: 一旦你定义了你要
Command option update
AD RMS to AD RMS to Azure Information Protection Part 1 The Scenario: So, you have read my previous blog posts about AD RMS side-by-side migration and Enterprise Migration from AD RMS to AIP using SCCM but unfortunately both of those articles assume best case scenario for the original AD RMS cluster. Sadly, that is not always the way things work. In the real world, the AD RMS instance may have been initially installed on Windows Server 2003 using RMS 1.0 and was subsequently upgraded to 2008 R2 keeping all of the settings pretty much the same. This usually means using http only and having no CNAMEs for AD RMS or SQL. This makes my happy articles on upgrading to newer versions of AD RMS or to AIP a lot less straightforward. Let's fix that. The Setup: Luckily, most of the concepts for migration are the same as what I documented in the previous two articles, so I am going to happily plagerize reuse the content in those articles to make something new. This a
Enhancements to SQL Server Backup to Cloud in SQL Server 2012 SP1 CU4
SQL Server 2008 R2 Feature Pack is now available https://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52 This includes SQL Server Native Client 2008 R2. SQL Server code-named "Denali" Native Client supporting ODBC 3.8 We're excited to announce that Denali SNAC CTP1 adds support for the ODBC 3.8 features of the Microsoft ODBC DM (Driver Manager) introduced in Windows 7 and Windows Server 2008 R2. Please refer to https://blogs.msdn.com/b/data/archive/2009/07/06/odbc-dm-3-80-in-windows-7-and-windows-server-2008-r2.aspx for a blog posting detailing the ODBC DM changes. The ODBC 3.8 features supported in Denali SNAC are: Streamed Output Parameters Support retrieving output parameters in parts via SQLGetData when the output parameter was bound using SQLBindParameter . This is extremely valuable when working with large data objects, such as varbinary(max), varcha
Comments
Post a Comment