Showing posts with label what can i do with powershell. Show all posts
Showing posts with label what can i do with powershell. Show all posts

Saturday, February 19, 2011

What can I do ... part11 System Administration Tasks

System Administration Tasks


The following articles provide a brief introduction to carrying out system administration tasks by using Windows PowerShell; these tasks include such things as starting and stopping services, retrieving data using WMI, and managing event logs and event log events. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.

Using the Get-Service Cmdlet

Listing Service Information

This will probably shock you, but - just in case - you better sit down: the Get-Service cmdlet is designed to retrieve information about the services installed on your computer. (And to think that some people say Windows PowerShell is too complicated!) Do you want information about all the services installed on your computer? Then just call Get-Service without any additional parameters:
Get-Service
Here’s the kind of information you’ll get back:
Status   Name               DisplayName
------   ----               -----------
Running  AdobeActiveFile... Adobe Active File Monitor V4
Stopped  Alerter            Alerter
Running  ALG                Application Layer Gateway Service
Stopped  AppMgmt            Application Management
Running  ASChannel          Local Communication Channel
Alternatively, you can take advantage of the Windows PowerShell filtering capabilities to return just a subset of the services installed on your computer. For example, this command takes the data returned by Get-Service and pipes it through the Where-Object cmdlet. In turn, Where-Object filters out everything except those services that are stopped:
Get-Service | Where-Object {$_.status -eq "stopped"}
In the preceding command, the $_. represents the object passed across the pipeline (that is, the collection of services and their properties), while status is simply the service property we want to filter on. And because we’re interested only in services that are stopped, we use the syntax -eq “stopped”. What if we were interested only in services that were running? In that case, we’d use this command:
Get-Service | Where-Object {$_.status -eq "running"}
So what kind of data will we get back when we request only services that are currently stopped? This kind of data:
Status   Name               DisplayName
------   ----               -----------
Stopped  Alerter            Alerter
Stopped  AppMgmt            Application Management
Stopped  aspnet_state       ASP.NET State Service
Stopped  BITS               Background Intelligent Transfer Ser...
Stopped  Browser            Computer Browser
By default Windows PowerShell returns services sorted in alphabetical order. By using the Sort-Object cmdlet, however, you can sort that returned data any way you want. For example, this command sorts services first by Status, and then by DisplayName:
Get-Service | Sort-Object status,displayname
Get-Service Aliases
  • gsv

Using the Get-Eventlog Cmdlet

Managing Event Logs and Event Log Events

The Get-EventLog cmdlet actually serves two purposes: it enables you to manage your event logs, and it also enables you to get at the events contained within those event logs.
For example, suppose you’d like some basic information about the event logs on your computer. In that case, make sure you include the -list parameter when calling Get-EventLog:
Get-EventLog -list
In return, you’ll get back information similar to this:
Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----
  15,168      0 OverwriteAsNeeded       5,279 Application
     512      7 OverwriteOlder            145 Credential Manager
     512      7 OverwriteOlder             12 MNP Toc Editor
  15,360      0 OverwriteAsNeeded          88 MonadLog
  15,360      0 OverwriteAsNeeded         324 PowerShell
  30,016      0 OverwriteAsNeeded      51,510 Security
  15,168      0 OverwriteAsNeeded       6,457 System
If you only want information about a specific event log then use the Where-Object cmdlet to limit data retrieval to the log whose LogDisplayName is equal to, say, System:
Get-EventLog -list | Where-Object {$_.logdisplayname -eq "System"}
As you can see, all you’ll get back is information about the System event log:
Max(K) Retain OverflowAction        Entries Name
  ------ ------ --------------        ------- ----
  15,168      0 OverwriteAsNeeded       6,458 System
But that’s just the beginning; as we noted, you can also use Get-EventLog to look at the events in your event log. For example, this command retrieves all the events in the System event log:
Get-EventLog system
That’s going to result in (depending on the number of records in your event log) a long scrolling list similar to this:
Windows PowerShell
More information than you really wanted, or needed? Then use the -newest parameter, and get back only the last x number of events recorded in the log. For example, this command retrieves the last three events written to the System event log:
Get-EventLog system -newest 3
Here’s the kind of data you’ll get back:
Index Time          Type Source                EventID Message
----- ----          ---- ------                ------- -------
 5811 May 13 09:42  Erro W32Time                    29 The time provider Ntp...
 5810 May 13 09:42  Warn W32Time                    14 The time provider Ntp...
 5809 May 13 09:13  Warn DnsApi                  11194 The system failed to ...
To get more detailed information, just pipe the returned data through the Format-List cmdlet:
Get-EventLog system -newest 3 | Format-List
That will bring back information like this:
Index              : 5811
EntryType          : Error
EventID            : 29
Message            : The time provider NtpClient is configured to acquire time from one or more
                     time sources, however none of the sources are currently accessible.
                     No attempt to contact a source will be made for 59 minutes.
                     NtpClient has no source of accurate time.
Category           : (0)
CategoryNumber     : 0
ReplacementStrings : {59}
Source             : W32Time
TimeGenerated      : 5/13/2006 9:42:22 AM
TimeWritten        : 5/13/2006 9:42:22 AM
You can also pipe data through the Where-Object cmdlet to return a subset of events. For example, this command retrieves only those events in the Windows PowerShell event log that have an EventID equal to 403:
Get-EventLog "Windows PowerShell" | Where-Object {$_.EventID -eq 403}
As you might expect, all we get back are events with an EventID equal to 403:
Index Time          Type Source                EventID Message
----- ----          ---- ------                ------- -------
   58 May 12 09:09  Info Windows PowerShell                403 Engine state is chang...
   34 May 10 15:39  Info Windows PowerShell                403 Engine state is chang...
   16 May 09 15:28  Info Windows PowerShell                403 Engine state is chang...
Here’s a nifty little command, one that retrieves all the events in the Windows PowerShell event log, then uses the Group-Object cmdlet to group those events by EventID. In other words, the command tallies up the total number of events for each ID (for example, two events with the EventID 300 occurred, six events with the EventID 400 occurred, etc.). That data is then piped through the Sort-Object cmdlet to provide results sorted by EventID. Here’s the command:
Get-EventLog "Windows PowerShell" | Group-Object eventid | Sort-Object Name
And here’s the results of running that command:
Count Name                      Group
----- ----                      -----
    2 300                       {TVSFRANK, TVSFRANK}
    6 400                       {TVSFRANK, TVSFRANK, TVSFRANK, TVSFRANK...}
    3 403                       {TVSFRANK, TVSFRANK, TVSFRANK}
   42 600                       {TVSFRANK, TVSFRANK, TVSFRANK, TVSFRANK...}
   21 601                       {TVSFRANK, TVSFRANK, TVSFRANK, TVSFRANK...}


Using the Set-Service Cmdlet

Modifying the Properties of a Service

What can you do with the Set-Service cmdlet? We’re glad you asked. Set-Service provides a way for you to change the Description, StartupType, or DisplayName of a service. All you have to do is call Set-Service, followed by the name of the service you’d like to modify and the appropriate parameter (-description, -startup, -displayname). For example, this command changes the start mode for the ClipBook service to Manual:
Set-Service clipsrv -startuptype "manual"
Note. Other valid settings for StartupType are Automatic and Disabled.
This command changes the description of the ATI HotKey Poller service:
Set-Service "ati hotkey poller" -description "This is ATI HotKey Poller service."
As you can see, Windows PowerShell makes it possible for you to change the description; however, it doesn’t guarantee that you’ll come up with a good description!


Using the Resume-Service Cmdlet

Resuming a Paused Service

The Resume-Service cmdlet is used for resuming a service that is currently paused. (What’s the difference between a paused service and a stopped service? A stopped service drops all existing connections and refuses to take any new connections. A paused service will typically continue to service existing connections, but will not accept any new connections.)
To resume a paused service call Resume-Service followed by the service name (that is, the name of the service as stored in the registry):
Resume-Service tapisrv
Alternatively, you can add the -displayname parameter and resume the service using the service display name, the name that appears in the Services snap-in:
Resume-Service -displayname "telephony"

Using the Get-WMiObject Cmdlet

Retrieving Data Using WMI

At this point in time there are only a few cmdlets (Get-Process, Get-Service, and Get-EventLog) designed for carrying out system administration tasks. Because of that, WMI remains the primary automation technology for system administration, so system administrators will likely rely heavily on Get-WmiObject to help them with their routine management tasks.
And there’s an added bonus, too: unlike most cmdlets, Get-WmiObject can be run against remote computers. That means you really can use Windows PowerShell as a management tool.
By default, Get-WmiObject binds to the root\cimv2 namespace on the local computer, making it extremely easy to return property values for any class found in cimv2. For example, suppose you need information from the Win32_BIOS class. OK:
Get-WmiObject win32_bios
You get the idea: just call Get-WmiObject followed by the class name. Ah, you say, but what if that class is located on a remote computer? No problem; just add the -computername parameter followed by - you guessed it - the name of the remote computer (atl-fs-01):
Get-WmiObject win32_bios -computername atl-fs-01
Still not convinced? Good point: we did say that, by default, Get-WmiObject connects to the root\cimv2 namespace. Is there any way to connect to a class found in a different namespace? Of course there is: just include the -namespace parameter followed by the complete namespace path (e.g., root\ccm, not just ccm). For example, this command returns information from the SMS_Client class, which resides in the root\ccm namespace:
Get-WmiObject -namespace root\ccm -class sms_client -computername atl-fs-01
It should go without saying that you can use other cmdlets in conjunction with Get-WmiObject (although we seem to have said it anyway). For example, this command retrieves information from the CCM_InstalledComponent class on the remote computer atl-fs-01. The command then pipes that data to Select-Object, which filters out all properties except three: DisplayName, Name, and Version. In turn, that filtered data is passed to Sort-Object, which sorts the information by DisplayName. Here’s what the command looks like:
get-wmiobject -namespace root\ccm -class ccm_installedcomponent -computername atl-fs-01 | Select-Object displayname,name,version | Sort-Object displayname
And here’s the kind of data you get back:
displayname                name                       version
-----------                ----                       -------
CCM Framework              CcmFramework               2.50.4160.2000
CCM Policy Agent           CcmPolicyAgent             2.50.4160.2000
CCM Status Agent           CcmStatusAgent             2.50.4160.2000
SMS Client Core Components SmsClient                  2.50.4160.2000
SMS Inventory Agent        SmsInventory               2.50.4160.2000
SMS Remote Control Agent   SmsRemoteTools             2.50.4160.2000
SMS Shared Components      SmsCommon                  2.50.4160.2000
SMS Software Distributi... SmsSoftwareDistribution    2.50.4160.2000
SMS Software Metering A... SmsSoftwareMetering        2.50.4160.2000
SMS Software Update Agent  SmsSoftwareUpdate          2.50.4160.2000
SMS Source List Update ... SmsSourceUpdateAgent       2.50.4160.2000
On the other hand, there will likely be times when you don’t want a filtered set of properties and their values; instead, you’d just like to see everything Win32_BIOS has to offer. To ensure that you get back information on all the properties (and their values) your best bet is to pipe the data returned by Get-WmiObject to Select-Object, then use the wildcard character * to indicate that you want back all the property values:
Set-WmiObject win32_bios | Select-Object *
If you don’t want all the system properties (like __SUPERCLASS and __RELPATH) then add the -excludeproperty parameter and use the wildcard character to filter out any properties whose name begins with an underscore character:
Get-WmiObject win32_bios | Select-Object -excludeproperty "_*"
Bonus tip. WMI itself is actually pretty easy to use; what isn’t always so easy is figuring out the properties and methods for a specific WMI class. Check that: that’s what used to be difficult. With Windows PowerShell you can simply use Get-WmiObject to connect to the class in question (for example, Win32_BIOS), and then pipe that information through the Get-Member cmdlet:
Get-WmiObject win32_bios | get-member
And what will that do for you? That will show you the properties and methods of Win32_BIOS, including:
BiosCharacteristics       Property              System.UInt16[] BiosCharacte...
BIOSVersion               Property              System.String[] BIOSVersion ...
BuildNumber               Property              System.String BuildNumber {g...
Etc.
Get-WmiObject Aliases
  • gwmi

Using the Get-Process Cmdlet

Retrieving Process Information

The Get-Process cmdlet provides a quick and easy way to retrieve information about the processes running on your computer. To get a quick overview of all the processes currently running on your machine simply call Get-Process without any parameters:
Get-Process
By default, you’ll get back data similar to this:
Windows PowerShell
Believe it or not, that’s all it takes. Only interested in the instances of Microsoft Word that are running on your computer? Then call Get-Process followed by the executable file name (without the file extension). In other words:
Get-Process winword
That results in output similar to this:
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    565      25    48760      77744   537   241.34   3116 WINWORD
Want to get back more than one process? Then just specify more than one executable name, separating the names with commas:
Get-Process winword,explorer
This time around your output will return information about both Word and Windows Explorer:
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    497      16    18524      28264    96     8.30   1080 explorer
    565      25    48760      77744   537   241.34   3116 WINWORD
Alternatively, you can use a wildcards to retrieve information about, say, all the running processes whose executable file name starts with the letter w:
Get-Process w*
With this command you get back pretty much what you’d expect to get back:
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     65       2     1628       1836    15     0.03   2024 wdfmgr
    557      65     8184       3824    57     1.06   1220 winlogon
    569      26    48748      77912   542   282.86   3116 WINWORD
    149       4     2024       5288    37     0.17    808 wmiprvse
     48       2      916       3404    29     0.06   2820 WZQKPICK
Although the functionality of the Get-Process cmdlet overlaps with the functionality of the WMI class Win32_Process, Get-Process can retrieve additional information not exposed through WMI, including properties such as company, file version, and product version. For example, this command pipes Get-Process through the Select-Object cmdlet, filtering out everything except the process name and the properties just mentioned:
Get-Process | Select-Object name,fileversion,productversion,company
Here’s the kind of information you can expect to get back:
Name                FileVersion         ProductVersion      Company
----                -----------         --------------      -------
alg                 5.1.2600.2180 (x... 5.1.2600.2180       Microsoft Corpor...
apdproxy            3.0.0.53237         3.0.0.53237         Adobe Systems In...
asghost             1.5.0.035           1.5                 Cognizance Corpo...
ati2evxx            6.14.10.4118        6.14.10.4118.02     ATI Technologies...
Note. Because of the length of some of these property values, you might want to pipe the output through the Format-List cmdlet.
So how do you know which process properties are available through Get-Process? Probably the easiest way to determine that is to simply call Get-Process and then pipe the returned information through the Get-Member cmdlet:
Get-Process | Get-Member
That will return a list of all of the cmdlet’s properties and methods.
Get-Process Aliases
  • gps
  • ps

Using the Stop-Service Cmdlet

Stopping a Running Service

The Stop-Service cmdlet is used for stopping a service that is currently running. To stop a service, simply call Stop-Service followed by the service name (that is, the name of the service as stored in the registry):
Stop-Service btwdins
Alternatively, you can add the -displayname parameter and stop the service using the service display name, the name that appears in the Services snap-in:
Stop-Service -displayname "Bluetooth service"
Stop-Service Aliases
  • spsv
Using the Start-Service Cmdlet

Starting a Stopped Service

The Start-Service cmdlet is used for starting a service that is currently stopped. To start a service, simply call Start-Service followed by the service name (that is, the name of the service as stored in the registry):
Start-Service btwdins
Alternatively, you can add the -displayname parameter and start the service using the service display name, the name that appears in the Services snap-in:
Start-Service -displayname "Bluetooth service"
Start-Service Aliases
  • sasv
Using the Stop-Process Cmdlet

Terminating a Process

Stop-Process enables you to terminate a process (or processes). You can indicate the processes you want to kill either by specifying the process ID or by specifying the process name. For example, this command stops the process with the process ID 3512:
Stop-Process 3512
To stop a process by process name, use the -processname parameter followed by the process name (minus the file extension). For example, to terminate all instances of Notepad use this command:
Stop-Process -processname notepad
And, yes, Stop-Process accepts wildcard characters, too. For example, this command terminates any instances of Notepad, as well as any other processes whose names start with note:
Stop-Process -processname note*
Stop-Process Aliases
  • spps
  • kill

Thursday, February 17, 2011

What can I do with windows powershell part10

Scripts and Applications


The following articles provide a brief introduction to working with scripts and applications while using Windows PowerShell; these tasks include such things as running scripts and/or applications as well as measuring how long it takes a Windows PowerShell task to complete. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.

Using the Invoke-Item Cmdlet

Opening a File or Running a Program

The Invoke-Item cmdlet provides a way to run an executable file or to open a file (or set of files) from within Windows PowerShell. For example, this command opens Calculator:
Invoke-Item c:\windows\system32\calc.exe
Note. Yes, by default you must specify the entire path to the executable file.
This command, meanwhile, opens all the .txt files found in C:\Scripts:
Invoke-Item c:\scripts\*.txt
To tell you the truth, the latter example - using Invoke-Item to open multiple items at once - is probably the best use of this cmdlet. If all you want to do is open a single document or launch a single program, that can be done just by typing the document/application name and pressing ENTER. Want to start Notepad? This command will do that for you:
notepad
Note. Interestingly enough, you don’t need to specify the entire file path if you start a program without actually calling Invoke-Item. Of course, that’s true only if the application is in your Windows path.
Want to open the file C:\Scripts\Test.txt in Notepad (or whatever program you use as the default editor for .txt files)? Then just type in the path to the file:
c:\scripts\test.txt
Invoke-Item Aliases
  • ii
Using the Invoke-Expression Cmdlet

Running a Windows PowerShell Script

The Invoke-Expression cmdlet provides one way to run a script from within Windows PowerShell. For example, this command runs the script C:\Scripts\Test.ps1:
Invoke-Expression c:\scripts\test.ps1
Alternatively you can use the ampersand to indicate that you want to run a script:
& c:\scripts\test.ps1
Or, even easier, just type in the path to the script:
c:\scripts\test.ps1
In all cases any paths that include blank spaces must have the entire path enclosed in double quote marks:
Invoke-Expression "c:\my scripts\test script.ps1"
Invoke-Expression Aliases
  • iex
Using the Measure-Command Cmdlet

Timing How Long it Takes a Script or Command to Run

For better or worse people are often concerned with the running time of their scripts and their commands. If you’ve ever wondered how long it takes to perform a specific task then the Measure-Command cmdlet is exactly what you’ve been looking for: it enables you to measure the running time of a command or script down to the millisecond. (Actually, it even enables you to measure the running time beyond a millisecond. But at that point ….)
To use Measure-Command, simply call the cmdlet, using the command or script to be run as the cmdlet parameter (make sure you enclose the value within curly braces). For example, this command runs the Get-Service cmdlet and then exports the data to an XML file named C:\Scripts\Test.xml; at the same time, it also keeps track of the time it takes for the command to complete:
Measure-Command {Get-Service | Export-Clixml c:\scripts\test.xml}
When you run this command, service information will be saved to the file Test.xml; in addition, Measure-Command will report back information similar to this:
Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 980
Ticks             : 9807034
TotalDays         : 1.13507337962963E-05
TotalHours        : 0.000272417611111111
TotalMinutes      : 0.0163450566666667
TotalSeconds      : 0.9807034
TotalMilliseconds : 980.7034
To perform this same feat with a script simply pass the name of that script as the Measure-Command parameter. This command runs the script C:\Scripts\Test.ps1, and - as a bonus - reports back the running time as well:
Measure-Command {c:\scripts\test.ps1}
Here’s what we get back:
Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 971
Ticks             : 9717422
TotalDays         : 1.12470162037037E-05
TotalHours        : 0.000269928388888889
TotalMinutes      : 0.0161957033333333
TotalSeconds      : 0.9717422
TotalMilliseconds : 971.7422
As you can see, at least in this case there’s no practical difference between running the command from the Windows PowerShell console and running that very same command from a Windows PowerShell script.

What can I do with windows powershell part9

Windows PowerShell Sessions


The following task-based articles provide a brief introduction to retrieving and managing Windows PowerShell sessions; these tasks include such things as retrieving the Windows PowerShell history and re-invoking a command contained within that history. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.

Using the Get-Culture Cmdlet

Listing Language and Locale Information

The Get-Culture cmdlet does only one thing: it returns language and locale information. For example, on an English language computer Get-Culture returns the following information:
LCID             Name             DisplayName
----             ----             -----------
1033             en-US            English (United States)
To retrieve this information simply type Get-Culture without any additional parameters:
Get-Culture


Using the Get-History Cmdlet

Listing the Current Windows PowerShell History

During each session Windows PowerShell keeps track of all the commands you type in the console window. Retrieving a list of those commands is as easy as calling the Get-History cmdlet:
Get-History
By default Windows PowerShell keeps track of the most recent 64 commands typed in the console window; when you invoke the Get-History cmdlet only the 32 most recent of those commands are displayed (e.g., commands 33 through 64). So how do you view commands 1 through 32? In that case you tell Get-History to start with command 32 and count backwards (using the -count parameter) 32 times. Don’t worry; that sounds more complicated than it really is:
Get-History 32 -count 32
Incidentally, for any given Windows PowerShell session you can change the number of commands that Windows PowerShell keeps track of; that can be done by modifying the $MaximumHistoryCount variable. For example, would you prefer that Windows PowerShell keep track of your last 150 commands? Okey-doke:
$MaximumHistoryCount = 150
Get-History Aliases
  • ghy
  • h
  • history
Using the Invoke-History Cmdlet

Re-running a Previous Command

The Invoke-History cmdlet enables you to re-execute a Windows PowerShell command simply by specifying the ID number assigned to that command. (How can you determine the ID number assigned to a command? Use the Get-History cmdlet.) For example, suppose you issued a fairly complicated command at the beginning of your Windows PowerShell session, a command you now need to issue again. Instead of retyping the command (and running the risk of typing it incorrectly), run Get-History to determine the command ID (say, 3). Then simply call Invoke-History followed by the ID number:
Invoke-History 3
The Invoke-History cmdlet accepts only a single ID. What if you’d like to execute two or more previous commands, in rapid-fire succession? In that case, simply issue a pair of Invoke-History commands, separating the two using a semi-colon:
Invoke-History 3;Invoke-History 4
Invoke-History Aliases
  • ihy
  • r
Using the Add-History Cmdlet

Restoring a Previously-Saved Windows PowerShell History

So you’re working in Windows PowerShell and you’ve just typed in a series of commands that perform a very useful task. Those commands are saved in the Windows PowerShell history, but now it’s time to go home. As you know, the moment you exit the Windows PowerShell console that history will be erased. In turn, that can mean only one thing: the next time you want to carry out that same task you’ll have to remember - and re-type - all those commands.
Or will you? Suppose - just suppose - that before you exit PowerShell you use this command to save your current history as an XML file named C:\Scripts\My_History.xml:
Get-History | Export-Clixml "c:\scripts\my_history.xml"
Why bother saving your Windows PowerShell history? Here’s why. The next time you fire up Windows PowerShell you can use the Import-Clixml cmdlet to reload that XML file. Once you’ve done that you can then pass the contents of that file to the Add-History cmdlet. Lo and behold, at that point your old history (the set of commands saved in My_History.xml) will magically be restored to your current history. Here’s what the command to do that looks like:
Import-Clixml "c:\scripts\my_history.xml" | Add-History
Maybe one of those cool before and after picture sets will help. Let’s suppose we conducted a Windows PowerShell session and, at the end, exported the history file. We now start a brand-new Windows PowerShell session; because we haven’t done anything yet, the history is blank:
Windows PowerShell
Next we import the saved history file and call the Add-History cmdlet. Now take a look at the Windows PowerShell history:
Windows PowerShell
It’s the next-best thing to having your own time machine!

What can I do with windows powershell part8

Windows PowerShell Drives and Namespaces


The following articles provide a brief introduction to working with Windows PowerShell drives and namespaces; these tasks include such things as adding and removing Windows PowerShell drives and navigating through Windows PowerShell namespaces. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.

Using the Get-Location Cmdlet

Checking Your Location in a Windows PowerShell Namespace

The Get-Location cmdlet simply lets you know where you are within the various Windows PowerShell drives. For example, this command:
Get-Location
Returns information similar to this:
Path
----
C:\Documents and Settings\kenmyer
If you’d like to know the current location in a different drive, just use the -psdrive parameter following the call to Get-Location. For example, this command leaves you in your current location, but tells you where you would be if you used Set-Location to switch to the HKCU drive:
Get-Location -psdrive hkcu

Get-Location Aliases
  • gl

Using the New-PSDrive Cmdlet

Creating a New Windows PowerShell Drive

The New-PSDrive cmdlet functions similar to the Subst command: it enables you to map a drive (in this case, of course, a Windows PowerShell drive letter) to a path. For example, this command creates a new Windows PowerShell drive (drive X) that’s mapped to the folder C:\Scripts:
New-PSDrive -name X -psprovider FileSystem -root c:\scripts
As you can see, New-PSDrive takes three parameters:
  • -name, which is the name to be given the new drive. We called our drive X primarily because that’s easy to type, but you can give the drive any name you want (just stay away from blank spaces and any restricted characters).
  • -psprovider, which simply indicates the type of drive being created. Because our new drive is part of the file system, we use the FileSystem parameter. For other types of drives (such as registry drives) you’ll need to use other providers. Fortunately, you can get a list of drive providers by calling the Get-PSDrive cmdlet.
  • -root, which is, in this case, the folder that serves as the drive root. When we use the command Set-Location x, we’ll end up in C:\Scripts, the root of our new drive.
The upshot? Now you can switch to the C:\Scripts folder merely by typing this command:
Set-Location x:
If that wasn’t enough, keep in mind that you aren’t limited to creating new drives mapped to the file system; instead, you can map drives within any Windows PowerShell namespace. For example, this command maps Windows PowerShell drive Y to the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion key in the registry:
New-PSDrive -name Y -psprovider Registry -root HKCU:\Software\Microsoft\Windows\CurrentVersion
To access that registry key from now on you merely need to type Set-Location y:
Mapped drives last only as long as your current Windows PowerShell session. If you exit PowerShell and then restart it, your mapped drive will no longer be available. To ensure that your new drive survives between Windows PowerShell sessions, create a PSConfiguration folder in your Windows PowerShell profile folder. For example:
C:\Documents and Settings\gstemp\My Documents\PSConfiguration

Note. How are you supposed to know your Windows PowerShell profile folder? Just type this command:
Get-Variable profile | Format-List
In the PSConfiguration folder, create a file named Microsoft.PowerShell_profile.ps1 and add the following command to the file:
New-PSDrive -name X -psprovider FileSystem -root c:\scripts
The next time you start a Windows PowerShell session drive X will be available to you. (Think of the profile file as being a sort of autoexec.bat file for Windows PowerShell.)
New-PSDrive Aliases
  • ndr
  • mount
Using the Get-PSDrive Cmdlet

Listing Your Windows PowerShell Drives

Windows PowerShell maps a number of “drives” that make it easy for you to navigate various namespaces on your computer; by default this includes not only the physical disk drives on your computer but also such things as the registry hives HKEY_CURRENT_USER (drive HKCU) and HKEY_LOCAL_MACHINE (drive HKLM). To return a list of all the Windows PowerShell drives on your machine, simply use the Get-PSDrive cmdlet:
Get-PSDrive
In return, Windows PowerShell will return information similar to this:
Name       Provider      Root                                   CurrentLocation
----       --------      ----                                   ---------------
Alias      Alias
C          FileSystem    C:\                                 ...Settings\kenmyer
cert       Certificate   \
D          FileSystem    D:\
E          FileSystem    E:\
Env        Environment
Function   Function
HKCU       Registry      HKEY_CURRENT_USER
HKLM       Registry      HKEY_LOCAL_MACHINE
Variable   Variable
Alternatively, you might want to pipe these results into the Format-List cmdlet; when you do that, you’ll get back additional information (such as the full provider name) for each drive. That command looks like this:
Get-PSDrive | Format-List
And the returned data will look like this:
Name            : Alias
Description     : Drive containing a view of the aliases stored in session state.
Provider        : Microsoft.Windows PowerShell.Core\Alias
Root            :
CurrentLocation :

Name            : C
Description     :
Provider        : Microsoft.Windows PowerShell.Core\FileSystem
Root            : C:\
CurrentLocation : Documents and Settings\kenmyer
You can also specify an individual drive name (or use wildcard characters) to return information about a single drive or set of drives. This command returns information for only drive C:
Get-PSDrive c
And this command returns information for the two registry drives (both of which have names starting with the letter H):
Get-PSDrive h*

Get-PSDrive Aliases
  • gdr

Using the Set-Location Cmdlet

Navigating through Windows PowerShell Namespaces

The Set-Location cmdlet is roughly equivalent to the cd command found in Cmd.exe: it enables you to specify a new working location in a namespace. For example, this command sets the working location to C:\Scripts:
Set-Location c:\scripts
So why did we use clumsy terminology like working location rather than simply saying that Set-Location enables you to set the current working folder? That’s because, in Windows PowerShell, you aren’t limited to navigating through the file system (for more information, see the Get-PSDrive cmdlet). For example, this command places you in the HKEY_CURRENT_USER\Software\Microsoft\Windows portion of the registry:
Set-Location HKCU:\Software\Microsoft\Windows
Incidentally, not only can you use the alias cd as a shortcut method for calling Set-Location, but you can also use the commands cd .. to move to the parent location and cd \ to move to the drive root.
Set-Location Aliases
  • sl
  • cd
  • pwd
  • chdir
Using the Convert-Path Cmdlet

Translating a Windows PowerShell Path

The Convert-Path cmdlet converts a Windows PowerShell path to a system path. What does that mean, and does it even matter? Well, suppose you’ve created a new Windows PowerShell drive (drive X). That drive letter is valid only in Windows PowerShell; you can’t switch to Windows Explorer and access drive X. Convert-Path, however, can tell you the “real” path of drive X. In other words, if you run this command:
Convert-Path x:
You’ll get back information similar to this:
C:\Scripts
This is particularly useful with registry drives. Windows PowerShell has its own syntax for indicating registry paths; for example, to use the Set-Location cmdlet to switch to the registry you would use a command similar to this:
Set-Location hkcu:\software\microsoft\windows
That’s fine, but outside of Windows PowerShell a path like hkcu:\software\microsoft\windows is meaningless. If you need to reference that path outside of Windows PowerShell, then just ask Convert-Path to lend you a hand:
Convert-Path hkcu:\software\microsoft\windows
That command gives you the actual path within the registry:
HKEY_CURRENT_USER\software\microsoft\windows

Convert-Path Aliases
  • cvpa
Using the Remove-PSDrive Cmdlet

Unmapping a Windows PowerShell Drive

Nothing lasts forever, which is as true for Windows PowerShell drives as it is for anything else. If you ever decide to get rid of a Windows PowerShell drive then simply call the Remove-PSDrive cmdlet, passing along the name of the drive to be removed. For example, this command removes drive Y:
Remove-PSDrive y

Remove-PSDrive Aliases
  • rdr

What can I do with windows powershell part7

Aliases


The following task-based articles provide a brief introduction to working with Windows PowerShell aliases; these tasks include such things as retrieving and remapping existing aliases as well as creating new aliases. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.

Using the New-Alias Cmdlet

Creating a New Windows PowerShell Alias

So you say that you like Windows PowerShell, but you have problems remembering some of the cmdlet names? Well, then why not create an alias for those cmdlets, an alias that you can remember? For example, maybe you’d prefer to type show instead of Get-ChildItem. If that’s the case, then you can use the New-Alias cmdlet to map the term show to Get-ChildItem. All you have to do is call New-Alias followed by the alias name (show) and the cmdlet the alias is being mapped to (Get-ChildItem). You know, something like this:
New-Alias show Get-ChildItem
Now, what do you suppose will happen the next time you type show in the Windows PowerShell console? You got it:
Windows PowerShell
By default, aliases are not saved between Windows PowerShell sessions: each time you restart Windows PowerShell you’ll need to recreate the alias. To ensure that your new aliases survive between Windows PowerShell sessions, create a PSConfiguration folder in your Windows PowerShell profile folder. For example:
C:\Documents and Settings\gstemp\My Documents\PSConfiguration
Note. How are you supposed to know your Windows PowerShell profile folder? Just type this command:
Get-Variable profile | Format-List
In the PSConfiguration folder, create a file named Microsoft.PowerShell_profile.ps1 and add the following command to the file:
Set-Alias show Get-ChildItem
That should do the trick.
New-Alias Aliases
  • nal

Using the Import-Alias Cmdlet

Importing Saved Windows PowerShell Aliases

If you can export all your Windows PowerShell aliases using the Export-Alias cmdlet then it seems only fitting and proper that you can import those aliases using the Import-Alias cmdlet. To import a saved alias file simply call Import-Alias followed by the file path:
Import-Alias c:\scripts\alias.txt
Note that Import-Alias does not delete or overwrite any existing Windows PowerShell aliases. For example, suppose you have an alias named xyz that maps to the Get-ChildItem cmdlet. Let’s further suppose that your text file also has an alias named xyz, this one mapping to the Get-Help cmdlet. When you import the file your version of xyz will not be overwritten; instead, Windows PowerShell will inform you that an alias named xyz already exists, and leave well enough alone. Import-Alias will only import aliases (based on name) that don’t currently exist in your Windows PowerShell environment.
Import-Alias Aliases
  • ipal

Using the Get-Alias Cmdlet

Listing All Your Windows PowerShell Aliases

The Get-Alias cmdlet simply returns a list of your Windows PowerShell aliases. Type the following, and all your aliases will be displayed on-screen:
Get-Alias
If you don’t want to see all the aliases you can use the -name parameter and specify either a single alias name or use a wildcard to return a group of aliases. For example, this command returns a list of all the aliases that start with the letter F:
Get-Alias -name f*
Like we said, you’ll get back information similar to this:
CommandType     Name                            Definition
-----------     ----                            ----------
Alias           fc                              format-custom
Alias           fl                              Format-List
Alias           foreach                         foreach-object
Alias           ft                              Format-Table
Alias           fw                              Format-Wide
Get-Alias Aliases
  • gal

Using the Export-Alias Cmdlet

Saving Windows PowerShell Aliases

The Export-Alias cmdlet provides a way to export your Windows PowerShell aliases to a text file. In its simplest form you can just call Export-Alias along with the path to the text file. For example, this command exports your alias file as a comma-separated values list, saving the file as C:\Scripts\Test.txt:
Export-Alias c:\scripts\test.txt
The resulting text file will look similar to this:
# Alias File
# Exported by : kenmyer
# Date/Time : Saturday, May 06, 2006 4:12:53 PM
# Machine : TVSFRANK
"ac","Add-Content","","ReadOnly, AllScope"
"clc","Clear-Content","","ReadOnly, AllScope"
"cli","clear-item","","ReadOnly, AllScope"
Alternatively, you can export your aliases as a script file, a file that uses a series of Set-Alias cmdlets (and thus a file that can be run as a Windows PowerShell script in order to configure those aliases). To do that, tack on the -as parameter, setting the value to “script”. That command looks like this:
Export-Alias c:\scripts\test.ps1 -as "script"
And the resulting file looks like this:
# Alias File
# Exported by : kenmyer
# Date/Time : Saturday, May 06, 2006 4:14:04 PM
# Machine : TVSFRANK
set-alias -Name:"ac" -Value:"Add-Content" -Description:"" -Option:"ReadOnly, AllScope"
set-alias -Name:"clc" -Value:"Clear-Content" -Description:"" -Option:"ReadOnly, AllScope"
set-alias -Name:"cli" -Value:"clear-item" -Description:"" -Option:"ReadOnly, AllScope"
Just for the heck of it, you might also want to export a single alias or set of aliases. For example, suppose you’ve created a set of aliases, each one starting with the letter X. To export these aliases as a script (thus making it easy for someone else to configure those same aliases on their computer) use the -name parameter along with the wildcard X*:
Export-Alias c:\scripts\test.ps1 -name x*  -as "script"
By default Export-Alias will overwrite any existing files with the same name; if a file named Test.txt already exists then Export-Alias will overwrite that file. To prevent that from happening, just add the -noclobber parameter:
Export-Alias c:\scripts\test.txt -noclobber
If you run this command and Test.xml already exists you’ll get back the following error message:
Export-Clixml : File C:\scripts\test.txt already exists and NoClobber was specified.
Export-Alias Aliases
  • epal

Using the Set-Alias Cmdlet

Remapping an Existing Windows PowerShell Alias

Set-Alias allows you to map an existing alias to a different cmdlet. For example, suppose you have an alias named show that, for some reason, is mapped to the Remove-Item cmdlet. You’d prefer that show be mapped to Get-ChildItem. Well, why didn’t you say so:
Set-Alias show Get-ChildItem
Just call Set-Alias followed by the alias name, followed by the appropriate cmdlet. That’s all you have to do.
Although there’s no corresponding cmdlet set aside for removing a mapped alias, you can achieve that task by using Remove-Item:
Remove-Item alias:\show

What can I do with windows powershell part6

Security and Security Descriptors


The following articles provide a brief introduction to carrying out security-related tasks by using Windows PowerShell; these tasks include such things as configuring the Windows PowerShell script execution policy and retrieving the digital signature or security descriptor from a file or folder. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.


Using the Set-ExecutionPolicy Cmdlet

Changing the Windows PowerShell Script Execution Policy

The Set-ExecutionPolicy cmdlet enables you to determine which Windows PowerShell scripts (if any) will be allowed to run on your computer. Windows PowerShell has four different execution policies:
  • Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  • AllSigned - Only scripts signed by a trusted publisher can be run.
  • RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  • Unrestricted - No restrictions; all Windows PowerShell scripts can be run.
To assign a particular policy simply call Set-ExecutionPolicy followed by the appropriate policy name. For example, this command sets the execution policy to RemoteSigned:
Set-ExecutionPolicy RemoteSigned


Using the Get-ExecutionPolicy Cmdlet

Listing the Windows PowerShell Script Execution Policy

The Get-ExecutionPolicy cmdlet simply tells you which of the four execution policies (policies that determine which Windows PowerShell scripts, if any, will run on your computer) is currently in-force. The Windows PowerShell execution policies include the following:
  • Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.
  • AllSigned - Only scripts signed by a trusted publisher can be run.
  • RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.
  • Unrestricted - No restrictions; all Windows PowerShell scripts can be run.
To determine the execution policy simply run the cmdlet without any parameters:
Get-ExecutionPolicy
To change the execution policy, use the Set-ExecutionPolicy cmdlet.


Using the Get-Acl Cmdlet

Retrieving the Security Descriptor for an Object

The Get-Acl cmdlet enables you to retrieve the security descriptor (access control list) for a file, a folder, or even a registry key. Note that, in order to view complete information for an object, you should pipe the results of Get-Acl through the Format-List cmdlet. For example, this command retrieves the security descriptor for the folder C:\Scripts, then displays that information as a list:
Get-Acl c:\scripts | Format-List
The resulting display will look something like this:
Path   : Microsoft.Windows PowerShell.Core\FileSystem::C:\scripts
Owner  : FABRIKAM\kenmyer
Group  : FABRIKAM\Domain Users
Access : BUILTIN\Administrators Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  FullControl
         FABRIKAM\kenmyer Allow  FullControl
         CREATOR OWNER Allow  268435456
         BUILTIN\Users Allow  ReadAndExecute, Synchronize
         BUILTIN\Users Allow  AppendData
         BUILTIN\Users Allow  CreateFiles
Audit  :
Sddl   : O:S-1-5-21-1454471165-1004336348-1606980848-8183G:DUD:(A;OICIID;FA;;;B
         A)(A;OICIID;FA;;;SY)(A;ID;FA;;;S-1-5-21-1454471165-1004336348-16069808
         48-8183)(A;OICIIOID;GA;;;CO)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A
         ;CIID;DC;;;BU)
Had we called Get-Acl without piping the results through Format-List the resulting display would have looked more like this:
Path                       Owner                      Access
----                       -----                      ------
Microsoft.Windows PowerShell.Co... BUILTIN\Administrators     FABRIKAM\kenmyer Allow ...
Not quite as easy to decipher, to say the least.
Right, we did mention that Get-Acl can return the security descriptor for a registry key, didn’t we? This command returns security information for HKEY_CURRENT_USER\Software\Microsoft\Windows:
Get-Acl HKCU:\Software\Microsoft\Windows
You can also use wildcard characters to retrieve a set of objects. Need to review the security settings for all the .log files in C:\Scripts? Here you go:
Get-Acl c:\scripts\*.log | Format-List


Using the Get-AuthenticodeSignature Cmdlet

Retrieving Digital Signatures

The Get-AuthenticodeSignature cmdlet enables you to retrieve information about the digital signature (if any) that was used to sign a file. For example, this command retrieves any digital signatures used on the Windows PowerShell executable file:
Get-AuthenticodeSignature "C:\Program Files\Windows PowerShell\v1.0\Windows PowerShell.exe"
And here’s the type of data that comes back:
SignerCertificate                         Status             Path
-----------------                         ------             ----
564E01066387F26C912010D06BD78D3CF1E845AB  Valid              Windows PowerShell.exe
If a file (such as C:\Scripts\Test.txt) has not been digitally signed then you’ll get back data similar to this:
SignerCertificate                         Status             Path
-----------------                         ------             ----
                                          UnknownError       test.txt