We solve 9 Windows Server 2008 management tasks using PowerShell. Part 1
- Recovery mode
Sometimes, using PowerShell, you can manage Windows Server 2008 much faster than with the usual GUI tools. In this article, you will find the 9 most common tasks that can be implemented using PowerShell. (10, the task was excluded from the translation due to the fact that the script demonstrated in the article was incomplete - Note by the translator ).
There will be two posts on this topic. There is a lot of material, the material is good, but, unfortunately, placement in one post will make it unreadable.
So, what tasks will be considered:
- Changing the local administrator password using PowerShell
- Rebooting or shutting down the server
- Service restart
- Process stop
- Generate Disk Usage Report
- We get the last 10 errors of the event log
- Reset folder access control
- Get server's uptime
- Get Service Pack Information
The first five tasks we will consider in this post, the remaining 4 subsequent ones. Interested parties are welcome to cat.
1. Change the password of the local administrator
Suppose you logged in as a domain administrator on a computer running Windows 7 that is part of your domain. Now, suppose you want to change the local administrator password on the remote CHI-WIN7-22 server in Chicago. After using the password for a certain period of time, it is advisable to change it; the procedure must be repeated periodically.
The first thing an administrator does to change the administrator password is to create an ADSI object for the local administrator on this computer. This is done in PowerShell as follows:
This will retrieve the administrator account on the CHI-WIN7-22 server and assign it to the ADSI object $ Admin. The WinNT name on this line is case sensitive, take this into account. If you want to connect to another computer, simply replace CHI-WIN7-22 with the name of the computer you would like to connect to.
However, first you need to find out how long the password is used to determine whether it is time to change it or not. Information from $ Admin can be obtained as follows:
The time elapsed since the last password change is displayed. The result is shown in seconds, translate it into days (divide by 86400 (the number of seconds in days)):
Notice that the Value property was used . This was done because PasswordAge is stored as a collection, and therefore we need to first set the value of this collection to return it to the number to which the division operation can be applied.
In the end, you can change the password by calling the SetPassword method and then using the new password as an argument.
Attention: By pressing Enter, do not wait for a confirmation letter. That will not be! Changes will be applied immediately. What I demonstrated here is a method, not a cmdlet. Among other things, this means that unlike cmdlets, SetPassword does not support -whatif or - confirm .
It's all. Let me demonstrate all this PowerShell-based pictures.
2. Rebooting or stopping the server
We move on. We are faced with the task of restarting or stopping the server using PowerShell. As in the first case, suppose that you are logged in as a domain administrator on a Windows 7 machine that is part of your domain.
We will use two WMI cmdlets - Restart-Computer and Stop-Computer . Although we will not show them here, it is worth mentioning that these cmdlets accept alternate credentials. Alternative credentials allow you to specify a user account (different from the one under which you are logged in), so that you can carry out actions to which this (alternative) account has rights.
Also among the pleasant things about these cmdlets - you can use-whatif and - confirm . This means if you want to restart or shut down the server, you must first make sure that you do this on the computer intended for this. This is convenient when you perform similar operations with many computers.
To restart the computer, the syntax is:
Restart-Computer “CHI-DC02”, “CHI-FP01”
The following is actually a screenshot of PowerShell in which we used the –whatif argument . Use it if you just want to see what happens if you run the command.
Everything is quite simple. Let's complicate the task now. Suppose you have a list of computers in the servers.txt file . Use the Get-Content cmdlet to extract their names from the file.
So, you have a number of computers that you would like to restart from time to time, and you store their names in a text file. Every time you need to reload them, you simply use the Get-Content cmdlet . The following is an example of how Get-Content and Restart-Computer work .
First we get the contents of the file using Get-Content . To begin, we ping this computers. In this expression, we will run test-connection , which is actually equivalent to ping on each computer. -quiet returns true or false, and -count 2 means that each computer will be “pinged” only twice. Those computers that will be successfully pinged will be further put into operation.
Then we use foreach . The purpose of this is: for each name that passes the ping test, a message is displayed in green text indicating a restart of the computer. “$ _” Means the current object in the pipeline. Then use the Restart-Computer cmdletto reboot those computers that ping. We also use the –force parameter to reset everyone who is logged in to this computer –whatif
parameter is used to see what happens without actually restarting the computers.
3. Service reboot
Restart-Service , as the name implies, is a cmdlet that restarts a service. Although it does not have the ability to connect to a remote server, PowerShell Remoting can be activated , so you can run it locally on a remote computer. This is useful when you want to restart a service on a group of computers.
To restart the service locally, simply write Restart-Service “service ”, where “service” is the name of the service you want to restart. On the other hand, if you want to restart services on one or more remote machines, use the Invoke-Command cmdlet and PowerShell Remoting .
The screenshot below shows two examples of how the Restart-Service cmdlet works to restart the wuauserv service (Windows Update). In the first example, Restart-Service runs locally. In the second, it runs on the remote database server CHI-DB01 using the Invoke-Command cmdlet .
By default, Restart-Service does not display any objects unless you use the -passthru parameter . Additional information (Status, Name and more) is the result of its use. If the service is running on multiple computers and you want to restart them as well, list them with commas.
The same can be done using WMI. Create a WMI object:
gwmiIs short for Get-WmiObject .
Let's look at the methods of the object. We introduce the Get-Member (abbreviated as gm ).
As you may have noticed, there is no method to restart the service. This means that you first have to stop the services through the StopService method and start again using StartService .
Here's how to stop the service using the StopService method of the object. A parenthesis indicates the availability of a method. If you get ReturnValue equal to 0, then the service has stopped successfully. Otherwise, refer to the MSDN documentation for the Win32 service class.
Starting the service - StartService method.
Check: run the get-service command on this computer. Get-service allows you to get service information on a remote computer. Example request for remote computer CHI-DB01.
4. Stopping the process
Another common task is to stop the process. We use the Stop-Process cmdlet for this . It can be performed both locally and on a remote machine (see point 3).
There are two ways to stop a process using the Stop-Process cmdlet .
The first is simple. Start Stop-Process and pass it the name or the corresponding process ID. Please note that we stop “Calc” (Windows Calculator). In this example, the process is running locally.
The second method involves using the Get-Process cmdlet to retrieve one or more processes or transfer them to Stop-Process . For example, the Notepad process is taken. Killis an abbreviation for Stop-Process . Notepad is running locally.
We move on. Let's move on to the processes running on the remote machine. To start, let's start, for example, notepad on the remote computer chi-fp01.
Then, check if the process is running. For these purposes, we use ps , which is short for Get-Process .
5. Create a report on disk usage
Administrators should monitor the free space remaining on the servers. This can be done using WMI and the Win32_LogicalDisk class, which give us information such as device ID, disk size, free space and other information.
Through WMI, we can access local and remote computers. We can also fulfill these requests on one or several machines. We can also: export data to .csv or a database, create a text or HTML report, or simply display the results on the screen.
An example of a command executed on a local computer.
Get-WmiObject win32_logicaldisk -filter “drivetype=3” | Out-File c:\Reports\Disks.txt
We use the GetWmiObject cmdlet to return information from the Win32_LogicalDisk class. Then we use -filter to return only information for which the statement drivetype = 3 is valid, which means fixed logical drives, such as C :. This means that information regarding USB and network drives will not be included. The received information will be written to the Disks.txt file .
Example in PS.
Although everything seems to be fine, it’s better to make a couple of improvements. For example, add a display of free space in gigabytes, not bytes. This is what we will do.
To do this, create the Get-DiskUtil function. Although in the previous example we did everything interactively, in this case, let's write the function to a file, upload to your profile other scripts that you can use later.
And here is the function itself:
Let's take it apart.
The function takes the computer name as a parameter and sets it as the default local computer name.
Then we use a fragment of the Process script where the property “computer name” is passed to the function. “$ _” Indicates that the computer name is set as a variable. Otherwise, the computer name will be interpreted as a parameter.
The following is a GetWmiObject expression .
The output of this expression is passed to the Select-Object cmdlet (abbreviated Select) We use hash tables to create a custom property called Computername . In fact, the SystemName of the current object ($ _) will be renamed to Computername . DeviceID remains unchanged.
Let's make a couple of hash tables. The first takes the Size property and divides it by 1GB, the output will be with two decimal places and rename the property to SizeGB . The second produces the same with the Freespace property .
Then create the UsedGB property , which is not in WMI. The difference between the Size and FreeSpace properties is calculated and divided by 1GB.
In the end, create another PerFree property - free as a percentage. It completes the function.
Below is the operation of the function for the CHI-FP01 computer, displayed in a table ( Format-Table (or ft )) with auto formatting ( –auto parameter ).
Everything is so good, but from this function we can get more. Therefore, suppose you need to receive a weekly report on disk usage on all servers in your company. Let's see how this can be achieved.
First, save the results of our expression in the $ data variable so that we don’t type this command every time. Then, pass the results to the where object, ping the server (twice) and pass the computer name to the Get-DiskUtil function we created .
The data will be stored in the $ data variable . You can extract information from $ data and sort by computername using –auto . Information can also be sent to print ( Out-Printer ) or to a file ( Out-File ).
Convert to csv:
Then you can import this csv file to get a snapshot of the disk usage status at the time the command is run:
And finally: I will show how to create an HTML report that can be accessed from anywhere.
We take $ dataand pass it to the Sort Computername . The result is passed to the ConvertTo-HTML cmdlet . You can assign a title and CSS path. CSS is necessary because ConverToHTML does not have formatting capabilities. So if you want the report to look decent, you need a CSS file. At the last stage, we write the result to a file.
Now the file is ready, it can be viewed using the start command .
Sample HTML report.
Remember that information must be kept up to date.
The post contains a translation of the article from the portal petri.co.il
Top 10 Server 2008 Tasks done with PowerShell - Part 1
See the second part of the translation here.
PS Could not help but pay attention that the same task of obtaining information about free disk space can be solved using our free program NetWrix Disk Space Monitor.
You can see how the program works on youtube , download it here , and you can activate a free license without an expiration date (and generally without any restrictions) using the following data:
License name: NetWrix Disk Space Monitor Freeware License
License count: 1000000
License code: EhEQEhoaEhEQEhYTEhYaExQa