PowerShell实战指南 实验回顾

纵豆蔻词工,青楼梦好,难赋深情。

实验回顾 1-6 章

Get-EventLog -LogName Security -Newest 100 | Sort-Object -Descending -Property TimeGenerated | ConvertTo-Html | Out-File sec.html
Get-Process | Sort-Object -Descending -Property VM | Select-Object -First 5

Screen Shot 2018-05-16 at 8.08.55 PM.png

Get-Service | Select-Object -Property Name,Status | Sort-Object -Descending -Property Status | Export-Csv services.csv
Set-Service -Name "BITS" -StartupType Manual
Get-ChildItem -LiteralPath "C:\" -Include "Win*.*" -Recurse

Screen Shot 2018-05-17 at 10.31.28 PM.png

Get-ChildItem -Path "C:\Program Files" -Recurse > C:\Dir.txt
Get-EventLog -LogName Security -Newest 20 | Format-Custom
Get-EventLog -LogName Security -Newest 20 | ConvertTo-Xml
Get-Service | Select-Object -Property Name,DisplayName,Status | ConvertTo-Html -PreContent "Installed Services"
New-Alias -Name "D" -Value "Get-ChildItem"
Export-Alias -Path "c:\d.txt" -Name "D"
Import-Alias -Path "c:\d.txt"

导出的别名文件内容如下:

# 别名文件
# 导出者 : Administrator
# 日期/时间 : 2018年5月18日 20:15:28
# 计算机: iZubw3nsaoh3v6Z
"D","Get-ChildItem","","None"

在新的窗口中测试:

Screen Shot 2018-05-18 at 8.16.09 PM.png

这里补充一下,Get-EventLog仅适用于传统事件日志。若要从使用Vista及更高版本中的事件日志技术的日志中获取事件,用Get-WinEvent命令。

Get-EventLog -List

Screen Shot 2018-05-18 at 8.21.58 PM.png

Get-Location
Get-History -Id 9 | Invoke-History
Limit-EventLog -LogName "Security" -OverflowAction "OverwriteAsNeeded"
New-Item -ItemType "Directory" -Path "C:\Review"
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
Stop-Computer
Restart-Computer
Remove-Computer
Restore-Computer
Checkpoint-Computer

注:这些命令都可通过Get-Command *Computer*查到。

Set-ItemProperty

实验回顾 1-14 章

Display a list of running processes in a table that includes only the process names and ID numbers. Don’t let the table have a large blank area between the two columns.

Get-Process | 
Format-Table -Property processname,id -AutoSize

Run this:

Get-WmiObject -class Win32_UserAccount

Now run that same command again, but format the output into a table that has Domain and UserName columns. The UserName column should show the users’ Name property, like this:

Domain   UserName
=======  ========
COMPANY  DonJ

Make sure the second column header says UserName, and not Name.

Get-WmiObject -class Win32_UserAccount |
Format-Table -Property Domain,@{l='Username';e={$_.Name}} -AutoSize

Screen Shot 2018-06-13 at 2.55.33 PM.png

Have two computers (it’s OK to use localhost twice) run this command:

Get-PSProvider

Use Remoting to do this. Ensure that the output includes the computer names.

Invoke-Command -ComputerName localhost,localhost -command {Get-PSProvider}

Use Notepad to create a file named C:\Computers.txt. In that file, put the following:

Localhost
localhost

You should have those two names on their own lines in the file—two lines total. Save the file and close Notepad. Then write a command that will list the running services on the computer names in C:\Computers.txt.

Invoke-Command -ComputerName (Get-Content .\computers.txt) -command {Get-Service | Where-Object -FilterScript {$_.Status -like "runn*"}}

Query all instances of Win32_LogicalDisk. Display only those instances that have a DriveType property containing 3 and that have 50 percent or more free disk space.

Hint: to calculate free space percentage, it’s freespace/size * 100.

Note that the –Filter parameter of Get-WmiObject cannot contain mathematical expressions.

Get-WmiObject Win32_LogicalDisk | 
Where-Object -FilterScript {$_.drivetype -eq 3 -and ($_.freespace / $_.size) -gt 0.5}

Screen Shot 2018-06-13 at 3.44.19 PM.png

Display a list of all WMI classes in the root\CIMv2 namespace.

Get-CimClass -Namespace root\CIMv2

Display a list of all Win32_Service instances where the StartMode is Auto and the State is not Running.

Get-WmiObject win32_service | 
Where-Object -FilterScript {$_.startmode -eq "auto" -and $_.state -ne "running"} |
Format-List

Find a command that can send email messages. What are the mandatory parameters of this command?

Send-MailMessage

Run a command that will display the folder permissions on C:.

Get-Acl -Path c:\

Run a command that will display the permissions on every subfolder of C:\Users. Just the direct subfolders; you don’t need to recurse all files and folders. You’ll need to pipe one command to another command to achieve this.

Get-ChildItem C:\Users | Get-Acl

Screen Shot 2018-06-13 at 3.43.22 PM.png

Find a command that will start Notepad under a credential other than the one you’ve used to log into the shell.

Start-Process -FilePath notepad -Credential xxx

Run a command that makes the shell pause, or idle, for 10 seconds.

Start-Sleep 10

Can you find a help file (or files) that explains the shell’s various operators?

help *operators*

Screen Shot 2018-06-13 at 3.42.55 PM.png

Write an informational message to the Application event log. Use a category of 1 and raw data of 100,100.

Write-EventLog -LogName Application -EntryType Information -RawData 100,100 -Category 1 -EventId 1 -Message "hello" -Source msiinstaller

Run this command:

Get-WmiObject –Class Win32_Processor

Study the default output of this command. Now, modify the command so that it dis- plays in a table. The table should include each processor’s number of cores, manufacturer, and name. Also include a column called “MaxSpeed” that contains the processor’s maximum clock speed.

Get-WmiObject -Class Win32_Processor |
Format-Table -Property NumberofCores,Manufacturer,Name,@{l='MaxSpeed';e={$_.MaxClockSpeed}} -AutoSize

Screen Shot 2018-06-13 at 3.42.19 PM.png

Run this command:

Get-WmiObject –Class Win32_Process

Study the default output of this command, and pipe it to Get-Member if you want. Now, modify the command so that only processes with a peak working set size greater than 5,000 are displayed.

Get-WmiObject -Class Win32_Process | 
Where-Object -FilterScript {$_.PeakWorkingSetSize -gt 5000}

实验回顾 1-19 章

Create a list of running processes. The list should include only process name, ID, VM, and PM columns. Put the list into an HTML-formatted file named C:\Procs.html. Make sure that the HTML file has an embedded title of “Current Processes”. Display the file in a web browser and make sure that title appears in the browser window’s titlebar.

Get-Process | 
Select-Object -Property Name,Id,VM,PM |
ConvertTo-Html -Title "Current Processes" |
Out-File C:\Procs.html

Screen Shot 2018-06-13 at 5.34.59 PM.png

Create a tab-delimited file named C:\Services.tdf that contains all services on your computer. “`t” (backtick t inside double quotes) is PowerShell’s escape sequence for a horizontal tab. Include only the services’ names, display names, and statuses.

我想到的方法不太优雅,还用到了追加重定向:

Get-Service |
Select-Object -Property Name,DisplayName,Status |
ForEach-Object -Process {$line = $_.Name + "`t" + $_.DisplayName + "`t" + $_.Status; $line >> Services.tdf}

不过最终能够达到目的:

Screen Shot 2018-06-13 at 5.46.18 PM.png

参考答案很优雅:

Get-Service |
Select-Object -Property Name,DisplayName,Status | Export-CSV c:\services.tdf –Delimiter "`t"

竟然是替换掉csv格式默认的逗号…..

结果也比我的专业:

Screen Shot 2018-06-13 at 5.49.27 PM.png

不过最终哪个更好用,也不好说。我觉得我生成的文档更简洁,方便程序调用。

Repeat task 1, modifying your command so that the VM and PM columns of the HTML file display values in megabytes (MB), instead of bytes. The formula to calculate mega- bytes, displaying the value as a whole number, goes something like $_.VM / 1MB –as [int] for the VM property.

Get-Process | 
Select-Object -Property Name,Id,@{l="VM(MB)";e={$_.VM / 1MB -as [int]}},@{l="PM(MB)";e={$_.PM / 1MB -as [int]}} |
ConvertTo-Html -Title "Current Processes" |
Out-File C:\Procs.html

Screen Shot 2018-06-13 at 5.53.21 PM.png

总结

这本书的学习到这里就结束了。感谢作者Don Jones和Jeffery Hicks。感谢同济大学图书馆。译者也辛苦了,虽然这翻译并不好。