Share this page : facebooktwitterlinkedinmailfacebooktwitterlinkedinmail
Run old command in Powershell

Powershell combined a lot of command from cmd, Linux into one interface. You can use some linux command such as ls, ps, note not all the Linux command, this is done via alias, you can use get-alias to check which are available.

Invoke Operator: run a command that contains a space in its name, enclose its filename in single- quotes (‘) and precede the command with an ampersand (&).

Run programs in current directory:

PowerShell, like most Unix shells, requires that you explicitly state your desire to run a program from the current directory. To do that, you use the .\Program.exe syntax.

To save themselves from having to type the location of commonly used scripts and programs, many users put commonly used utilities along with their PowerShell scripts in a “tools” directory, which they add to their system’s path.

If you want PowerShell to automatically look in your current working directory for scripts, you can add a period (.) to your PATH environment variable.

 

To escape the whole command invocation, use the verbatim argument marker (–%) to prevent PowerShell from interpreting any of the remaining characters on the line.

E.g .

PS > $username = "Lee"

PS > cmd /c echo Hello $username with 'quotes' "and" $variables @{ etc = $true }

    Hello Lee with quotes and System.Collections.Hashtable

PS > cmd /c echo Hello $username `

    --% with 'quotes' "and" $variables @{ etc = $true }

    Hello Lee with 'quotes' "and" $variables @{ etc = $true }
Structured Commands (Cmdlets)

 

In addition to supporting traditional Windows executables, PowerShell introduces a powerful new type of command called a cmdlet (pronounced “command-let”). All cmdlets are named in a Verb-Noun pattern.

Note that the cmdlet returns object instead of just string, which has method, properties. So you can use command such as (get-command stop-process).Definition.

Objects, properties, and methods

One of the fundamental features of Windows PowerShell is that cmdlets return objects.

An object is a thing that gives us the ability to either describe something or do something. If you are not going to describe or do something, then there is no reason to create the object. Depending on the circumstances, you may be more interested in the methods or the properties.

Script:

The running of scripts is disabled by default, use the Set-ExecutionPolicy cmdlet to change the PowerShell execution policy to one of the policies that allow scripts to run:

  Set-ExecutionPolicy RemoteSigned

The three arguments you can use to control execution are -whatif, -confirm, and suspend.

whatif

-whatif parameter after the cmdlet. This only works for cmdlets that change system state.

e.g.

Stop-Process -id 1056 -whatif

Confirm

 

Stop-Process -id 1768 -confirm

Suspending execution of a cmdlet

 

Suspend is useful for this scenario: you may be in the middle of stopping a number of processes, but you need to issue a command to view details on the processes to ensure you do not stop the wrong one.

 

1. Open Windows PowerShell, start an instance of Notepad.exe, identify the process, and examine the output, just as in steps 1 through 4 in the previous exercise. The output on my machine is shown following. Please note that in all likelihood, the process ID used by your instance of Notepad.exe will be different from the one on my machine.

       Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

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

            39       2      944        400    29     0.05   3576 notepad

2. Use the confirm argument to force a prompt when using the Stop-Process cmdlet to stop the Notepad process identified by the Get-Process note* command. This is illustrated here:

Stop-Process -id 3576 -confirm

The Stop-Process cmdlet, when used with the confirm argument, displays the following conformation prompt:

Confirm

Are you sure you want to perform this action?

Performing operation "Stop-Process" on Target "notepad (3576)".

[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):

3. To suspend execution of the Stop-Process cmdlet, enter s. A triple-arrow prompt will appear, as follows:

PS C:\>>>

Use the Get-Process cmdlet to obtain a list of all the running processes that begin with the letter n. The syntax is as follows:

Get-Process n*

On my machine, two processes appear. The Notepad process I launched earlier and another process. This is shown here:

             Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

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

                  39       2      944        400    29     0.05   3576 notepad

                  75       2     1776       2708    23     0.09    632 nvsvc32

5. Return to the previous con rmation prompt by typing exit. Once again, the con rmation prompt appears as follows:

Confirm

Are you sure you want to perform this action?

Performing operation "Stop-Process" on Target "notepad (3576)".

[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):

6. Type y and press Enter to stop the Notepad process. There is no further con rmation. The prompt now displays the default Windows PowerShell prompt, as shown here:

PS C:\>

Help

The first command you should issue after fire up the Powershell is update-help, because the power shell does not ship the help documents by default.

The help documentation will download the respective language edition according to your OS, so some module’s help may not available, which may result in error messages.

If you found some error messages and want to clean them:

Update-Help -Module * -Force -ea 0

It uses the ErrorAction parameter (ea is an alias for this parameter) with a value of 0. A 0 value means that errors will not be displayed when the command runs.

You can also determine which modules receive updated help by running the Update-Help cmdlet with the -verbose parameter. Unfortunately, when you do this, the output scrolls by so fast that it is hard to see what has actually updated. To solve this problem, redirect the verbose output to a text  file.

Get-command

To find the command according to keyword or part of keyword with wildcard operator.

Recall that the cmdlet follows Verb-Noun pattern, you can also find in this way:

specify the -noun argument. Use o* for the noun. This is shown here: gcm -noun o*

The previous command will return all the cmdlets that contain a noun that begins with the letter o. This result is as follows:

CommandType                  Name                                               ModuleName

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

Function                     Add-OdbcDsn                                        Wdac
 
Function                     Disable-OdbcPerfCounter                            Wdac

Function                     Enable-OdbcPerfCounter                             Wdac
Get-member

This will show all the property and method of an object. e.g. show the property and method of Get-childitem, use get-childitem | get-member.

To only see properties available for the Get-ChildItem cmdlet, use the -membertype argument and supply a value of property. Use tab completion this time, rather than the gci | gm alias. This is shown here:

 Get-ChildItem -Force | Get-Member -membertype property

To only see the method:

Get-ChildItem | Get-Member -membertype method

Or you can use another form to get the property and method:

Use the -inputobject argument to the Get-Member cmdlet to retrieve member de nitions of each property or method in the list. The command to do this is as follows:

  Get-Member -inputobject Get-ChildItem

New-object

Recall that there is an object called the wshShell object which is useful for network administrator:

wcript_Shell

$wshShell = New-Object -comobject "wscript.shell" 
$wshShell.run("calc.exe").       //open the calculator

show the location of windows folder and system drive

$wshShell.ExpandEnvironmentStrings("%windir%")

c:\windows

$wshShell.ExpandEnvironmentStrings("%systemdrive%")

c:
Powershell profile

A Windows PowerShell profile is a Windows PowerShell script that runs each time Windows PowerShell starts.

1. In a Windows PowerShell console, check your script execution policy: Get-ExecutionPolicy

2. If the script execution policy is restricted, change it to remotesigned, but only for the current user:

Set-ExecutionPolicy -Scope currentuser -ExecutionPolicy remotesigned

3. Review the description about Windows PowerShell execution policies, and enter Y to agree to make the change.

4. In a Windows PowerShell prompt, determine whether a profile exists by using the following command (by default, the Windows PowerShell profile does not exist):

fTest-Path $profile

5. If tests-profile returns false, create a new profile  le by using the following command:

New-Item -path $profile -itemtype file -force

6. Open the profile  file in the Windows PowerShell ISE by using the following command:

ise $profile

7. Create an alias in the profile named gh that resolves to the Get-Help cmdlet. This command appears here:

        Set-Alias gh Get-Help

8. Create a function that edits your Windows PowerShell console profile in ise. This function appears here:

    Function Set-Profile

    {

     Ise $profile

    }

9. Start the Windows PowerShell Transcript command via the Windows PowerShell profile. To do this, add the Start-Transcript cmdlet in Powershell (the Start-Transcript cmdlet creates a record of all Windows PowerShell commands, as well as the output from those commands, this is not issued in power shell ise).

    Start-Transcript

10. Save the modi cations to the Windows PowerShell console profile by pressing the Save icon in the tool bar, or by choosing Save from the File menu.

11. Close the Windows PowerShell ISE and close the Windows PowerShell console.

12. Open the Windows PowerShell console. You should now see the output in the console from starting the Windows PowerShell transcript utility.

13. Test the newly created gh alias.

To know the alias of an object:

get-alias | Where definition -match "Get-ChildItem"

Network module

$wshnetwork = New-Object -comobject “wscript.network”

$wshnetwork.EnumPrinterConnections()

$wshnetwork.EnumNetworkDrives()

$wshnetwork.UserName

$wshnetwork.UserDomain

$wshnetwork.ComputerName

Modify display
Select the columns (Properties)

use Select keyword with column name to select the columns you like. E.g. show the Physical memery, CPU, Process ID, and Process Name:

get-process | select PM,CPU,Id,ProcessName
Get-Printer | select Name,Type,DriverName

 

Some useful cmdlet

 

1.  Rename a computer:

Rename-computer –computername <old computername> -NewName <New computerName>