中国DOS联盟论坛

China DOS Union

-- Unite DOS · Advance DOS · Grow DOS --
Union site: www.cn-dos.net Forum site: www.cn-dos.net/forum
Guest | Log in | Register | Members | Search | China DOS Union
中国DOS联盟论坛
The time now is 2026-08-24 15:33
47,811 topics / 349,909 posts / today 0 new / 48,262 members
WinPE、PowerShell及其它命令行系统专区 » My messy PowerShell study notes
Printable Version  2,603 / 0
Floor1 tempuser Posted 2009-02-05 16:36
高级用户 Posts 261 Credits 547
A bit迷糊 after learning some, still at a loss. Is there any friend who has a clear feeling of getting started, let's study together!

Learning Questions:
1. How to arbitrarily display the method of a certain object and use it (already closed)?
2. How to use the command line uninstall string of uninstallable programs in PowerShell?

I. PowerShell Commonly Used Shortcuts
F7: Displays the command history that has been entered, and you can select and execute them one by one using the up and down arrows.
ALT+F7: Clears the command history.
ESC: Clears all characters currently entered.
CTRL+END: Clears the content from the cursor to the end of the line.
CTRL+C / CTRL+BREAK: Terminates the execution of the command.
↑: Queries historical commands upwards.
↓: Queries historical commands downwards.

II. Resource List
1. www.powershell.com
: Can download the PowerShell Plus tool, which is more convenient than the PowerShell tool provided by Microsoft. The latter has no auto-completion function.
2. forums.microsoft.com\china
3. PowerShell Blog: vista.itech.net
4. Install PowerShell: www.microsoft.com/downloads
5. PowerShell Development Team Blog http://blogs.msdn.com/PowerShell/
6. PowerShell Newsgroup Microsoft.Public.Windows.PowerShell
7. Script Center
http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspxPowerShell
8.

III. What is PowerShell
PowerShell is the future of system administration and scripting language development.
It is an interactive Shell environment (a new generation of command parser) and scripting language provided by Microsoft for the command line interface, enabling both command line users and script writers (by writing to COM objects to achieve many functions) to utilize the powerful functions of the.NET Framework (such as the class library of the.NET Framework - FCL), helping administrators complete flexible and automated work.
PowerShell is built on.NET, so it requires the support of.NET Framework v2.0 for installation.
PowerShell is object-based, and the output of commands is objects.
PowerShell is installed in %systemroot%\system32\
IV. Variables and Parameters in PowerShell
Variables in PowerShell should be understood as objects, not text.
The symbol for defining a variable: $. For example, to define a variable var, use $var. Assign a value to the variable: $var = 123 $var1 = abd. You can also embed variables into variables. For example, $var2 = "$var $var1", the value of $var2 is 123 abd. If it is $var2 = '$var $var1', then $var $var1 is assigned to $var2 as a string. Remember the difference between single quotes and double quotes.
For data types, you can not define and declare.
View all variables: get-variable
View the set of commands that can operate on variables: get-command –noun varibale
Common system variables: $pshome $home $profile
Four modes of variables: local script global private.
Example: Corresponding operations on environment variables
Get-childitem env:
Example: Specific reference to environment variables
$env:os
# Explanation: The system environment variables in CMD.EXE can still be used in PowerShell

-: Parameter lead character. For example, if there is a parameter Name, it must be written as -Name when writing.
Common parameters include: WhatIf Confirm Verbose Debug Warn ErrorAction ErrorVariable
OutVariable OutBuffer, they are all controlled by the PowerShell engine. Each time a cmdlet implements these parameters, their behavior is always the same.
-Syntax: Obtain the syntax of the cmdlet. For example, get-process –syntax

Important Parameter Explanation
-noun can obtain a series of commands that affect objects of the same type
-passthru can see the execution process of the command
-whatif can preview the possible consequences of the command. This parameter can realize the reference to the prototype pattern. Not every cmdlet can use this parameter.
-credential specifies the user account name
-eq equal operator. Adding I –ieq means case-insensitive comparison; -ceq case-sensitive comparison.
V. cmdlets and Skills in PowerShell
cmdlets naming rule:
A single cmdlet can only complete a single task. To complete complex tasks, it must be done through the pipeline |. | not only plays the role of passing the execution result of the previous cmdlet to the next cmdlet, but also plays the role of connecting commands, that is, commands can be written in multiple lines for easy reading.
| is executed concurrently.
Aliases: Aliases. For example, gps=get-process sort=sort-object ft=format-table. You can customize the alias of the command. The command is Get-Alias -Name gi -Value Get-Item. Note that system-defined aliases such as gi gcm scm cannot be changed.
Command abbreviation: For easy memory, Set is represented by S, Get by G, Item by I, Command by CM. For example, get-command=gcm; get-wmiobject=gwmi etc.
Get-command: Obtain all available cmdlets. Note that it does not include aliases function script, etc.
Example: Want to obtain detailed information of alias/ function /script commands
get-command –commandtype alias/function/externalscript
get-aliases: Obtain all aliases of commands.
get-help: Obtain help.
Example: Obtain the help information and its syntax of the command
get-help –name get-command –full/-detail -syntax
#-name: Can be omitted
get-process -?
Example: help or man display the help information of the command in pages
help get-service or man get-service
Example: Use the more function to display the help information in pages
get-process | more
# more can also read the content of the file and display it in pages, such as more c:\test.txt
Example: Display the help information of conceptual topics
get-help about_*
#about_: Represents the prefix of conceptual topics
get-help about_where
#Display the help information of the specific conceptual topic where
Example: get-command *_service
#Obtain the cmdlets related to service operation
#_ can be removed, written as *service, but the * cannot be removed. Writing get-command service will cause an error!
Example: Obtain a series of commands that affect the same type of object
get-command –noun service
#-noun: This parameter can obtain a series of commands that affect the same type of object, similar to get-command *service
Example: get-service | get-member
#If you want to fully understand the object structure of get-service, you can output this command to get-member through |
Example: Obtain some of the output objects of a certain command
get-process –name powershell | format-table –property processname,fileversion,starttime,name,id,company,path –autosize -wrap –groupby company
# -property is very useful for obtaining the information of the output object!
# -autosize means automatically adjusting the column width
# -wrap means automatically wrapping lines if the content cannot be displayed
#-width 2147483647 prevents the table from being truncated due to being too wide
# -groupby is used to control the table output, grouping based on the specified property value, which is easy to display a very large and difficult-to-display table
# -autosize and -wrap used together have a good display effect, but it consumes a lot of system resources. It is recommended to put properties with relatively small widths such as name at the end
# If you want to display all properties, you can use * to represent
#
Example: Obtain the specific information of a certain service/process
get-service –name alerter/get-process -name powershell
Example: List all commands with the verb get
get-command –verb get
#verb: The meaning of the parameter
Example: List the folders and files in the current directory
get-childitem
#get-childitem c:\ List the directories and files under the C drive
#get-childitem c:\ | out-host Output the directories and files under the C drive to the screen. If there is a lot of output information, this operation consumes a lot of CPU and memory. You can use the -paging parameter to output one screen at a time.
#out-null: Shield the output; out-printer: Print the output
Example: Output control commands format-wide/format-list/format-table/format-custom
Example: Output control commands out-host/out-null/out-printer/out-file -Encoding ASCII –width 2147483647
get-process | format-table | out-file –filepath c:\test.txt
#Output get-process to c:\test.txt
#Note that out-file creates unicode by default. -Encoding ASCII changes the file to ASCII, which is convenient for tool processing of the output
#-width 2147483647 prevents the table from being truncated due to being too wide
Example: To view the object structure of get-process
get-process | get-member | out-host –paging
Example: To view a certain type of information in the object structure of get-process
get-process | get-member –membertype property
# MemberType allows using the following values: AliasProperty, CodeProperty, Property, NoteProperty, ScriptProperty, Properties, PropertySet, Method, CodeMethod, ScriptMethod, Methods, ParameterizedProperty, MemberSet and All.

Exploration and Discovery
Get-Help, Get-Command
Get-Member: View the "structure of the object", which is very important.

Object-Oriented Small Commands
Compare, Group, Measure, Select, Sort, Tee, Where
Format Control
Format-(Custom, List, Table, Wide)
Task-Oriented Commands
Process: get/stop(-process)
System Service: get/start/stop/suspend/resume/restart(-service)
Event Log: get-eventlog

Main Commands in CLI (Command Line Interface) (????---Not understood---????????)
– Shell Functions (CLI available code)
– PowerShell Scripts (.PS1)
– Native commands (.EXE, .BAT, etc.)
Use Whanif to preview the execution result: For example, shutting down a process will have an impact on the system, so use it to preview first.
$?: Test whether the command is executed successfully.
Key Point:
Not all commands that conform to the "verb-noun" command specification are cmdlets of PowerShell. For example, clear-host is an internal function of PowerShell. You can judge whether its commandtype is function or cmdlet by get-command –name clear-host.
In addition to cmdlets being built-in commands of PowerShell, aliases function scirip executable files and external files of registered file type handlers all belong to the commands of PowerShell.
PowerShell has no auto-completion function, but can be extended by TAB. The condition is that after entering "verb + hyphen -", press the TAB key to automatically find the first matching command. If it is not the one you need, you can complete it through TAB again.
VI. Commands for File System Operations
get-location: Obtain the current directory
set-location –path c:\: Change the current directory to c:\, but there is no process prompt
set-location -path c:\ -passthru ##Change the current directory to c:\, with process prompt
set-locaiton \\server\shared directory: server remote server
push-location -path “local settings”: Push the current directory into the stack and change the directory to local settings
push-location -path temp: Push the current directory into the stack and change the directory to temp
pop-location -passthru: Restore the directory pushed into the stack. You can use it to pop the most recently used directory
cd –path hkcm:\software: Change the current directory to hkcm:\software

PowerShell uses the noun "item" to represent the content under the drive. If it is a file system drive, the item can be "folder or file or PowerShell drive".
Common operation commands for items: new-item rename-item copy-item remove-item invoke-item
invoke-item: Execute the item, which is a handler with the default application in the registry (similar to associated programs)
Example: invoke-item c:\1.txt
# Call notepad.exe to open 1.txt because the default associated program for txt is notepad.exe
invoke-item c:\windows
# Is equivalent to "double-click to open the windows directory", associated with the resource manager
invoke-item c:\test.bat
# Execute the bat
Example: Create 1.txt #new-item –path c:\1.txt –itemtype file/directory
Example: Rename 1.txt under the C drive to 2.txt under the D drive
rename-item –path c:\1.txt d:\2.txt
# This command is wrong because rename cannot move the directory, only rename within the same directory
# Correct: move-item –path c:\1.txt –destination d:\2.txt –passthru #Can see the specific moving process
Example: Copy a directory
copy-item –path c:\new –destination c:\temp
# Note that if there is content under new, the content cannot be copied to temp. Without parameters, only the container is copied
copy-item –path c:\new –destination c:\temp –recurse –force –passthru
# -recurse means copying the content inside the container as well
Example: Delete a directory
remove-item –path c:\temp –recurse
# If there is no -recurse, deleting the directory requires confirmation
# -recurse has different meanings under different commands
get-command –noun item: Obtain all operation commands for items
get-childitem: Used to enumerate "folders/files/registry".
Example: set-location c:\windows
get-childitem









*.dll
# Using -exclude **.dll is to exclude DLLs compatible with "win95 or 16-bit windows"
# But I didn't display the DLLs compatible with "win95 or 16-bit windows" on my own machine. I think this is related to the use environment of windows. The design statement must be rigorous and comprehensive
Example: get-childitem –path c:\windows\*.dll –recurse –exclude *.dll
# This statement will not return any results because the wildcards in *.dll will exclude all DLLs
#get-childitem –path c:\windows –include *.dll –recurse –exclude *.dll

Wildcards
* ? and
Among them, means matching the enclosed characters
Example: get-childitem c:\windows\*
# Means enumerating all files starting with x or z under the c:\windows directory
Example: get-childitem c:\windows\?????.log
# Means enumerating all 5 arbitrary character log files under c:\windows
VII. WMI Object Operations
WMI is the core technology of system management. WMI classes describe manageable resources, and many classes have many properties.
get-wmiobject –list #Obtain the available WMI class resources locally or remotely
By default, get-wmiobject uses the root/imv2 namespace. If you need to specify the namespace, you must use -namespace
Example: get-wmiobject –list –computernaem 192.168.1.1 –namespace root
Example: Specifically use a certain WMI class win32_operatingsystem
get-wmiobject –class win32_operatngsystem –namespace root –computername
# Self-written command. The error is that win32_operatngsystem is missing i, and root should be root/cimv2
get-wmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 –ComputerName .
#. represents the style of WMI, representing the computer name
# If get-wmiobject has no parameters, the first parameter is class by default; the parameter namespace has the default namespace root/cimv2; for local operations, the parameter computername can be omitted
# This command line can be abbreviated as get-wmiobject win32_operatingsystem
Can view more properties of the class
get-wmiobject win32_operatingsystem | get-member –membertype property
View non-default properties
get-wmiobject win32_operatingsystem | Format-Table -Property TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles
Use wildcard abbreviation
get-wmiobject win32_operatingsystem | Format-table –Property total*,free*
# Change table to list to enhance the readability of the result

Use the where-object cmdlet pipeline to filter objects (using comparison operators)
In the pipeline, $_ represents the object in the pipeline; - represents the prefix of the comparison operator; {} encloses the script block; the parameter -filterscript is used for filtering.
Example: Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"} | Where-Object -FilterScript {$_.StartMode -eq "Manual"} | Format-Table -Property Name,DisplayName,pathname
This statement is equivalent to
Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript { ($_.State -eq "Running") -and ($_.StartMode -eq "Manual") } | Format-Table -Property Name,DisplayName

Use the foreach-object cmdlet to perform repeated operations on multiple objects
Example: Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {($_.FreeSpace)/1024.0/1024.0}

Use select-object to select objects
Example: get-wmiobject –class win32_logicaldisk | select-object –property name,freespace | get-member

Use sort-object to sort
Example: get-wmiobject –class win32_systemdriver | sort-object –property state,name | format-table –property name,state,started,displayname –autosize
# Sort the state and name properties output in format-tabel
# descending sort in reverse order
V. Operations on.NET Objects
Some components have.NET Framework and COM interfaces. PowerShell allows using these components to expand and enhance system management work
The.NET Framework is a class library containing many classes, such as System.Diagnostics.EventLog, which can manage event logs.
Example: $applog=new-object –typename system.diagnostics.eventlog –argumentlist application, computername/ip
# Store the object in a variable for easy calling
# Without -argumentlist, the log can be created but is empty. Adding parameters can manage the specific log
# Enter the variable $applog to see the number of logs
# –argumentlist application passes application as a parameter to the parameter -argumentlist, playing the role of a constructor
# computername/ip accesses remote logs
get-eventlog: View the log
Example: Obtain the methods / properties of the object
$application | get-member –membertype method/property
# Among them, a method obtained is clear
Clear log information
$application.clear()
# () must be added. clear() represents the method, to distinguish it from the same-named property
Example: View the latest three logs of applicatio
get-eventlog –logname application –newest 3
# The log types also include system security
VIII. Operations on.COM (Component Object Model) Objects
COM components include the libraries contained in WSH and Active X applications. new-object can operate on these components
New-object –comobject wscript.shell #Create a COM object
# Can also create WScript.Network, Scripting.Dictionary and Scripting.FileSystemObject
Example: Use the COM object to create a shortcut
$shorcut=new-object –comobject wscript.shell
# Create a COM object and save it to a variable
$shorcut | get-member
# Obtain the operation methods of the object, including createshortcut
$net=$shorcut.createshortcut(“c:\test.url”)
# Establish a storage path and name for the created shortcut
# Note that do not miss the suffix.url, it can also be.lnk, depending on the need; also remember that () is followed closely
$net.targetpath=”http://10.*.*.*”
# Establish content mapping for the created shortcut. Because it is.url, it maps to a website
$net.save()
# Store the shortcut. It will not be created successfully without storing
Example: Use the COM object to start an IE instance
The separately running COM object is called an Active X executable program.
$ie=New-object –comobject internetexplorer.application
# Create an IE instance using the internetexplorer ProgID, that is, internetexplorer.application
# This process runs independently
Get-process
# The above created IE instance is not visible, but it can be viewed through the process
$ie.visible=$true
# Make the IE instance visible
$ie.navigate(“http://www.sohu.com”)
# Use navigate to navigate to a specific website
$ie.document.body.innertext
# Retrieve text content in the web page
$ie.quit()
# Close IE
$ie | get-member
# After closing IE, this variable becomes invalid. You can check it through get-member
$ie=$null
# Clear the reference of the remaining variable
Remove-variable ie
# Completely clear this variable
Example: Create a non-standard COM object
New-object –comobject excel.application –strict
# -strict creates a non-standard COM object
Because get-member has an optional parameter –inputobject, so $shorcut | get-member can be rewritten as
get-member –inputobject $shorcut
Note that -inputobject will treat the parameter as a single item. So if there are multiple objects stored in variables, then
-inputobject will treat them as an array of objects.
VIII. Static Classes
Static classes: Not all.NET Framework classes can be used with new-0bject. The properties and methods in static classes are fixed and can only be referenced, not modified, such as System.Environment and System.Math.
Therefore, new-object system.environment is wrong.
The properties of static classes are also static. The static properties of static classes are referenced through ::.

Example: How to view the static properties of system.environment
| get-member –static
# Note that the content displayed with -static and without -static is different
# With -static, the static properties of system.environment are displayed
# Without, the runtimetype of system.environment is displayed
# | get-member –membertype property cannot display static properties
# The reason why is written instead of is that system is the default and can be omitted
Example: Application of static properties
::osversion

There are some identical methods in the static class system.math, which can be distinguished by parameters.
| get-member –static –membertype method
Example: ::sqrt(9)

VIII. Providers and Drives in PowerShell
Providers abstract the access data layer between PowerShell and drives, so that different drives can be interacted with under a unified mechanism. But actually, we don't feel the existence of providers.
Get-help –category provider #Obtain all provider types.
Name the PowerShell drive with the noun PSDrive.
There are four types of drives:
Filesystem file system drive: such as C: D:
Registry registry drive: such as HKLM: HKLU:
Certificate certificate drive: such as CER:
Env drive (environment variable drive): Env:
Variable drive (variable drive):
Custom drive: There are three conditions, 1. The name of the drive; 2. Psprovider; 3. Root is the corresponding path of the drive. Example New-PSDRIVE -name zgktest –psprovider registry –root hklm\software\microsoft\windows\current. Enter the command to enter this drive: cd zgktest: or set-location zgktest: -passthru. The command to view the content under this drive is dir.
get-psdrive: Obtain the list of all drives
get-psdrive –psprovider certificate: Obtain the specified certificate drive
# -psprovider: is to specify the provider, remember not to miss ps
remove-psdriver –name drivername: Delete the specified drive
The drives of PowerShell are for PowerShell's own use. The resource manager and cmd.exe cannot open the drives of PowerShell.
When PowerShell exits, the newly defined drive will disappear. You can export the new console through the export-console command, and then import it into a new session through the parameter psconsolefile.
VI. Execution Policy of PowerShell Scripts
The execution policy of PowerShell is divided into four types: Restricted, default, prohibits all script execution; AllSigned, only runs trusted scripts; RemoteSigned, all local scripts can be executed, regardless of whether they are trusted. If the script is downloaded from the Internet, it must be trusted; UnRestricted, all scripts can be executed.
Command to change the policy: set executionpolicy remotesigned, change the default policy from restricted to remotesigned.
Makecert.exe: Make a trusted security script (provided by Microsoft).
Steps to make a trusted script using makecert.exe:
1. Create a trust certificate: makecert -n "CN=MyRoot" -a sha1 –eku1.3.6.1.5.5.7.3.3 -r -sv root.pvk
root.cer –ss Root -sr localMachine
2. Export the trust certificate: makecert -pe -n "CN=MyCertificate" -ss MY –a sh1 -eku 1.3.6.1.5.5.7.3.3 –iv
root.pvk –c root.cer
3. Use the trust certificate to trust-sign the script: Set-AuthenticodeSignature D:\myscript.ps1 $cert
VII. Syntax and Operations
get-member: Obtain properties and methods. Example: $var1 | get-member Obtain the properties and methods of $var. $var. Use the TAB key to select the properties and methods of the variable.
Directional output: Use " > " to represent.
Comment: Use "#" to represent.
Quotation marks: Pay attention to the difference between "single and double" quotes.
VIII. PowerShell's Management of IIS
Requires the support of the IIS PowerShell provider plug-in.
PowerShell manages IIS7 better, and manages IIS6 relatively weakly, only being able to do some start/stop IIS operations.
Common syntax: start-webitem stop-webitem get-webitemstate
. Create a Web site
New-Item iis:\Sites\TestSite -bindings
@{protocol="http";bindingInformation=":80:TestSite"} -physicalPath
c:\test
#New-item iis:\Site\TestSite –bindings: Create a site TestSite and implement binding
# protocol=”http” Use http protocol
#bindinginfomation=”;80:TestSite” Map port 80 to site TestSite
# physicalPath c:\test: The physical path of the site is c:\test
• Create a Web application
New-Item 'IIS:\Sites\Default Web Site\DemoApp' -physicalPath
c:\test -type Application
#type Application: The type is an application
IX. How PowerShell Manages the System
Important commands: get-process and stop-process; get-service
Example: Stop all unresponsive programs
Get-Process | Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process
Example: Stop all other Windows PowerShell dialogs
Get-Process -Name powershell | Where-Object -FilterScript {$_.Id -ne $PID} | Stop-Process -
PassThru
Example: Suspend a service spooler
Suspend-service –name spooler
Example: Restart multiple services
Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service
# First obtain the service list, filter them, and then execute the restart

Get-wmiobject is the most important command for regular system management.
Example: Collect desktop-related information of the local computer
Get-WmiObject -Class Win32_Desktop -ComputerName .| Select-Object -Property *
# The information listed by the WMI class is very detailed, and it also includes "WMI metadata represented by double underscores"
# Can be filtered through select-object
#-computername can be omitted, and. behind represents the local computer name
Example: Collect BIOS information
Get-wmiobject –class win32_bios
Example: Collect CPU information
Get-wmiobject –class win32_processor
Get-WmiObject -Class Win32_Processor -ComputerName .| Select-Object -Property *
et-WmiObject -Class Win32_ComputerSystem -ComputerName .| Select-Object -Property SystemType
# Get a general description string of the processor series
Example: List the computer manufacturer and model
Get-wmiobject –class win32_computersystem
Example: Obtain the user logged in to the computer
Get-wmiobject –class win32_computersystem –property username | select-object –property username
#select-object –property username simplifies the output content
Example: List the installed patch information
Get-wmiobject –class win32_quickfixengineering –property hotfixid
#-property hotfixid filters more purposefully
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .-Property Hot
FixId | Select-Object -Property HotFixId
# The above statement will also return other data. Further narrow the range through Select-Object -Property HotFixId
Example: List all users and owners
Get-WmiObject -Class Win32_OperatingSystem -ComputerName .| Select-Object -Property NumberOfLicensedUsers,NumberOfUsers,RegisteredUser
Simplified to
Get-WmiObject -Class Win32_OperatingSystem -ComputerName .| Select-Object -Property *user*
Example: List disk space and remaining space
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
#drivertype=3 hard disk type
Example: Obtain login session information
Get-wmiobject –class win32_logonsession
Example: Obtain local time
Get-WmiObject -Class Win32_LocalTime -ComputerName .| Select-Object -Property *
Example: Obtain computer services
Get-WmiObject -Class Win32_Service -ComputerName .| Format-Table -Property Status,Name,DisplayName -AutoSize –Wrap
# Obtaining the local computer service list can use get-service, but win32_service can also operate remotely
Example: List applications using the Windows installer
Get-wmiobject –class win32_product
# Not all applications use the Windows installer service
Example: Find the cache location of Microsoft.NET FrameWork 2.0
Get-WmiObject -Class Win32_Product -ComputerName .| Where-Object -FilterScript {$_.Name -eq "Microsoft .NET Framework 2.0"} | Select-Object -Property *
Example: Same as above
Get-WmiObject -Class Win32_Product -ComputerName .-Filter "Name='Microsoft .NET Framework 2.0'"| Select-Object -Property *
# This statement uses WMI for filtering, that is, using WQL query language for filtering
# Special characters (such as spaces or equal signs) commonly used in WQL queries have special meanings in Windows PowerShell. Therefore, it is prudent to always put the value of the Filter parameter in a pair of quotes. You can also use the Windows PowerShell escape character, that is, the backquote (`), but it may not improve readability. The following command is equivalent to the previous command and returns the same result, but uses the backquote "`" to escape special characters instead of putting the entire filter string in quotes:
Get-WmiObject -Class Win32_Product -ComputerName .-Filter Name`=`'Microsoft` .NET` Framework` 2.0`' | Select-Object -Property *
Example: Query some specific properties of the Windows installer application
Get-WmiObject -Class Win32_Product -ComputerName .| Format-List Name,InstallDate,InstallLocation,PackageCache,Vendor,Version,IdentifyingNumber
If you only want to query the application name, it can be simplified as
Get-wmiobject –class win32_product | format-wide –column 1
Example: List all uninstallable applications (programs that can be seen in "Add/Remove")
# They correspond to the registry location HKLM\Software\Microsoft\Windows\CurrerntVersion\Uninstall
New-psdrive –name unins –psprovider registry –root hklm:\software\microsoft\windows\currentversion\uninstall
# Create a new drive unins, so that you can query
Get-childitem –path unins:
# Obtain the specific information of uninstallable applications
(Get-childitem –path unins:).length
# Obtain the number of uninstallable applications
Get-childitem –path unins: | foreach-object –process {$_.getvalue(“displayname”)}
# Display the name of uninstallable applications
# Get-ChildItem -Path Uninstall:| Where-Object -FilterScript { $_.GetValue("DisplayName") -eq " 360安全浏览器 1.35"} Note that the execution has no effect
(Get-WmiObject -Class Win32_Product -Filter "Name='瑞星在线杀毒'" -ComputerName .).InvokeMethod("unins",$null)
# Uninstall "瑞星在线杀毒" Note that it was not successful
#unins is the newly defined drive

Extract the uninstallstring property to obtain the command line uninstall string of the uninstallable program
Get-ChildItem -Path Unins:| ForEach-Object -Process { $_.GetValue("UninstallString") }
# Note that unins: must be the previously defined drive
Filter by name to obtain the command line uninstall string of the uninstallable program
Get-ChildItem -Path Uninstall:| Where-Object -FilterScript { $_.GetValue("DisplayName") -like "Win*"} | ForEach-Object -Process { $_.GetValue("UninstallString") }

Example: Remotely install an MSI application on the PC01 computer. The shared installation path must conform to UNC
(Get-WMIObject -ComputerName PC01 -List | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi")
#UNC Universal Naming Convention

Example: Upgrade the Windows installer application
Prerequisite: The name of the installed application to be upgraded; the path of the upgrade package
(Get-WmiObject -Class Win32_Product -ComputerName .-Filter "Name='OldAppName'").InvokeMethod("Upgrade","\\AppSrv\dsp\OldAppUpgrade.msi")

Log off the system: logoff or shutdown –l or (Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).InvokeMethod("Win32Shutdown",0)
#win32shutdown is the method

Shut down or restart the computer: tsshutdn.exe or shutdown.exe
Obtain the connected local printer: get-wmiobject –class win32_printer or
(New-Object -ComObject WScript.Network).EnumPrinterConnections()
# The latter can list "printers and used ports"
Add a network printer: (new-object –comobject wscript.network).addwindowsprinterconnection(“\\打印机的UNC路径“)
Set the default printer: (Get-WmiObject -ComputerName .-Class Win32_Printer -Filter "Name='HP LaserJet 5Si'").InvokeMethod("SetDefaultPrinter",$null) or
(New-Object -ComObject WScript.Network).SetDefaultPrinter('HP LaserJet 5Si')
Delete a printer connection: (New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5")

Obtain the computer IP address: get-wmiobject –class win32_networkadapterconfiguration –filter ipenabled=true | select-object –property ipaddress,macaddress
# Note that why ipaddress is enclosed in parentheses () is because ipaddress is an array
Obtain detailed configuration data of the network adapter IP: Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .| Select-Object -ExpandProperty IPAddress
# Can use the select-object –expandproperty parameter to expand ipaddress
Obtain more detailed data of the network adapter: Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .| Select-Object -Property * -ExcludeProperty IPX*,WINS*
# select-object –property sets property selection, -excludeproperty ipx* excludes relevant properties

Ping the computer: Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .| Select-Object -Property Address,ResponseTime,StatusCode
# Only use the statement before the pipeline, the feedback information is very messy
# statuscode status code 0 means ping is successful
Use an array to ping a series of computers:
1..254| ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='192.168.1."+ $_ + "'") -ComputerName .}| Select-Object -Property Address,ResponseTime,StatusCode
# The red part means the range of ping, 1..254 means an array
Ping multiple addresses:
"127.0.0.1","localhost","research.microsoft.com" | ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='" + $_ + "'") -ComputerName .}| Select-Object -Property Address,ResponseTime,StatusCode
# Because there are multiple addresses, you need to use foreach-object to ping multiple addresses separately
Generate a group of complete addresses: $ips=1..254 | foreach-object –process {“192.168.1.”+$_}
Set the specified DNS domain for the network adapter:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName .| ForEach-Object -Process { $_.InvokeMethod("SetDNSDomain", "fabrikam.com")}
# The red part is the specified DNS domain to be set, of course, it can be modified

Create a shared directory: net share tempshare=c:\temp /users:25 /remark:"test share of the temp folder"
# /users:number allows the number of users accessing the shared folder
#/remark:” “ comments on the shared folder
Delete the share: net share tempshare /delete

Map a network drive to the local: net use B:\\FPS01\users or
(New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users")
Map the local folder as a Windows accessible drive
Subst m: $env:programfiles
# Map the programfiles folder as drive m

Process files and folders
List all items under a certain drive: get-childitem –force c:\ -recurse
#-force lists hidden items or system items
#-recurse lists the content of all subfolders under the current drive
# Similar to dir in cmd.exe and ls in UNIX

Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object -FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
# List all executable files under the programfile folder that were modified after 2005-10-01 and have a size between 1M and 10M Note that the execution did not pass
Copy a file: copy-item –path c:\test.txt –destination c:\test.bat –force
#-force forces the copy regardless of whether the target file test.bat exists
Copy a folder: copy-item c:\temp\test1 –recurse c:\temp\test2
Copy selected items: copy-item –filter *.txt –path c:\temp –recurse –destination c:\temp1
# Copy all txt files under c:\temp, including those under subfolders, to c:\temp1
Back up using the COM class scripting.filesystem: (New-Object -ComObject Scripting.FileSystemObject).CopyFile("c:\boot.ini", "c:\boot.bak")

Create a new empty file: new-item –path ‘c:\test.txt’ –itemtype “file”
Create a new folder: new-item –path ‘c:\temp’ –itemtype “directory”
Delete files and empty folders: remove-item c:\test.txt ;remove-item c:\temp –recurse
# recurse does not require confirmation and directly deletes, including subfolders

Read text content: get-content -path c:\test.txt
# Execute this statement to display the content of c:\test.txt
#get-content cmdlet treats the content of the text as an array, and each line is an element
#(get-content –path c:\test.txt).length obtains the number of lines in the text.
# $txt=get-content –path c:\test.txt stores the text content in variable $txt
Example: Display the word count/character count/line (excluding blanks) of a certain DOC file
get-content test.doc | measure-object -word -character -line -ignorewhitespace

List registry items:
Get-chliditem –path hkcu: -force -recurse
Get-childitem –path registry::hkcu
Get-chliditem –path registry::hkey_current_user
Get-childitem –path Microsoft.powershell.core\registry::hkcu
Get-childitem –path Microsoft.powershell.core\registry::hkey_current_user
# The above statements have similar functions and display the content of the specified current item in the registry
#-force displays system items or hidden items; -recurse displays all subitems in the registry, and there are include, exclude, filter
#microsoft.powershell.core\registry indicates the default path of the registry provider, which can be abbreviated as registry
Example: The command finds all items in HKCU:\Software that have no more than 100 subitems and exactly 400 values
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object –FilterScript {($_.SubKeyCount -le 100) -and ($_.ValueCount -eq 400) } The test is not successful!

Obtain registry entry information
Get-itemproperty hkcu:\software\microsoft\windows\currentversion\run
#-itemproperty lists the information of the properties and property values of the item, that is, displays the information in the right window of the registry
#-childitem lists the information of the subitems under the current item, that is, displays the information in the left window of the registry if there is any!
# Here, -itemproperty can be changed to -item, but obviously the information provided by the previous parameter is more organized
Use the -name parameter to obtain the specified registry entry information
Example: Obtain the information of ctfmon.exe under hkcu:\software\microsoft\windows\currentversion\run
Get-itemproperty hkcu:\software\microsoft\windows\currentversion\run –name ctfmon.exe
# The above operation can also be completed using the reg command
Example: reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\run /v ctfmon.exe
# The same can be completed using the COM object wscript.shell
Example: (New-Object -ComObject WScript.Shell).RegRead("HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ctfmon.exe")
Copy an item
Example: Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu:
# Why is it not possible to copy from hkcu: to hklm: in reverse?
Create an item
New-item hkcu:\testnewcreate or new-item registry::hkcu:\testnewcreate
# Remember that there is no : in hkcu:\testnew, it should be changed to registry::hkcu\ testnewcreate
# If the newly created item has the same name as the existing item, it can be created forcefully through -force, and others are similar
Create an entry of the new item
Example: New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -PropertyType String -Value $PSHome
Use the value array of the path parameter to create registry entries in multiple locations
Example: new-itemproperty –path hkcu:\software\microsoft\windows\currentversion, hklm:\software\microsoft\windows\currentversion –name testzgk –property string –value “我爱你海红”
# Propertytype reference table
PropertyType values Meaning
Binary Binary data
DWord A valid UInt32 number
ExpandString A string that can contain dynamically expanded environment variables
MultiString Multiline string
String Any string value
QWord 8-byte binary data

Rename a registry entry
Example: Rename-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -NewName PSHome –passthru
#-passthru can see the renamed entry name

Delete an item
Remove-item hkcu:\testnewcreate or Remove-item registry::hkcu\ testnewcreate
Example: Delete all items under 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion
Remove-item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion
If you want to keep the HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion item and only delete all items inside it
Remove-item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\*
Delete an entry
Example: Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PSHome

CMD UNIX used commands corresponding to PowerShell commands and aliases
CMD command Unix command PS command PS alias
dir ls Get-ChildItem gci
cls clear Clear-Host (function) Not available
del、erase、rmdir rm Remove-Item ri
copy cp Copy-Item ci
move mv Move-Item mi
rename mv Rename-Item rni
type cat Get-Content gc
cd cd Set-Location sl
md mkdir New-Item ni
Not available pushd Push-Location Not available
Not available popd Pop-Location Not available

[ Contact the Union admin team - 中国DOS联盟 - Standard version ]
Sponsored by ifanr Inc | © 2001–2023