谁不希望他们能成为一个巫师并说出几句话来让神奇的事情发生?好吧(Well),我们无法向您展示如何成为一名巫师,但我们可以向您展示如何做一点计算机魔术。
如果您有一台装有Windows 7的(Windows 7)Windows计算机,那么您就有了PowerShell。此外,如果您有一台装有Windows 7的计算机,请出于安全考虑对其进行更新。
但这篇文章不仅适用于Windows用户。最新版本的PowerShell是免费的,可以在 Mac 和Linux计算机上安装和使用。
这很重要,因为您了解的有关PowerShell的知识现在几乎可以在任何计算机上使用。谁知道?您可能会将这项技能提升到一个新的水平,并冒险进入信息技术(Information Technology)领域。
什么是 PowerShell?
来自微软(Microsoft)的高科技回答是,它是一个“专为系统管理员设计的命令行外壳”。“听起来很(” Sounds)吓人。但事实并非如此。你会照顾你的电脑吗?是的,那么您就是您家的系统管理员。
您是否告诉您的计算机如何处理点击和击键?是的,因此可以将命令行 shell 视为您输入内容以告诉计算机要做什么的另一个窗口。你可以这样做。
PowerShell就像一种编程语言,但不像大多数语言那样神秘。它读起来真的很像普通的英语(English),这是微软(Microsoft)努力争取的,以便非程序员也能学会。
这是一种编写几行命令(称为脚本)的方式,可以让Windows操作系统执行您希望它执行的操作。然后,您可以将这些行保存在文件中并通过单击运行它或安排它定期运行。
你可以用 PowerShell 做什么?
PowerShell的高级点是能够自动执行任务,因此您不必浪费时间重复做平凡的事情。对于专业的系统管理员(Systems Administrator)来说,这可能类似于创建新用户,为他们生成密码,然后将包含详细信息的电子邮件发送给他们的新主管。
手动完成,通过点击和输入,该过程可能需要 5 分钟到一个小时或更长时间。使用正确的脚本,系统管理员(Systems Administrator)甚至可能不必执行其中的任何部分。
但是您想知道您可以在家中使用PowerShell做什么。(PowerShell)几乎所有你不喜欢一次又一次地做的事情。通过删除不需要的临时文件和日志文件,使用它来释放硬盘驱动器上的空间。
在您孩子的计算机上设置宵禁。重命名(Rename)或组织一堆文件。这就是PowerShell(PowerShell)的美妙之处。几乎(Almost)可以在计算机上执行的任何操作,都可以创建PowerShell脚本以通过单击或按计划自动运行和运行。
如何使用 PowerShell?
使用PowerShell(PowerShell)的最简单方法是在PowerShell 集成脚本环境 (ISE)(PowerShell Integrated Scripting Environment (ISE))中。您可以通过单击开始并在(Start)Windows 10的搜索栏中键入powershell ise来找到它。您应该看到它,如下所示。
我们第一次使用它时,我们将以管理员(Administrator)身份运行它。为此,您必须首先在您的计算机上拥有管理员权限。在“开始”菜单(Start Menu)中,右键单击PowerShell ISE,然后单击“以管理员身份运行”(Run as Administrator)。
您可能会收到一个用户访问控制(User
Access Control)( UAC ) 警告弹出窗口,询问您是否确定要执行此操作。单击是(Yes)。
现在您正在查看PowerShell IDE。窗口(1)((1))的顶部窗格是脚本窗格。这是您编写脚本的地方。窗口(2)((2))的底部窗格是控制台区域。测试脚本时,您将在此窗格中看到输出。
这也是您会看到错误消息的地方,这将帮助您修复并改进您的脚本。窗口右侧的窗格(3)是命令插件。将其视为您可以使用的所有PowerShell命令的字典。
PowerShell设置为不运行除了已经是(PowerShell)Windows一部分的脚本之外的任何脚本。您需要对其进行更改,以便可以运行自己的脚本。
在脚本窗口中,复制并粘贴以下内容:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
它的Set-ExecutionPolicy部分称为 cmdlet(发音为 commandlet)。Cmdlet 是强大的东西。把(Think)它们想象成你可以给Windows的短命令,Windows会做一堆更复杂的东西来满足你的命令。
一个类比是告诉你的孩子打扫他们的房间。简明扼要(Short)。如果您的孩子精通房间清洁,那么他们会去整理床铺,将衣物放入篮子中,将玩具和书籍搁置起来,甚至可能用吸尘器吸尘。他们明白 cmdlet Clean-YourRoom意味着这一切。
在窗口顶部,您会看到一个绿色箭头。
单击(Click)它以运行命令。
-ExecutionPolicy部分告诉Set-ExecutionPolicy要(-ExecutionPolicy)设置什么策略。它是一个参数。它的意思是,“我希望你在这些指导方针内工作,并专门做这件事。它告诉它使用RemoteSigned的特定策略。
RemoteSigned策略规定PowerShell不得执行或运行从Internet下载的任何脚本,除非它由受信任的发布者签名。
以一种迂回的方式,它告诉PowerShell可以运行任何本地创建的脚本,因为这些脚本不需要由远程受信任的发布者签名。现在,您的PowerShell脚本将能够运行您在计算机上编写的任何脚本。
让我们看一个删除临时文件的脚本。它不如CCleaner强大或彻底,但CCleaner也有其自身的一系列问题。
使用 PowerShell(Use PowerShell)在硬盘(Your Hard Drive)上创建空间(Create Space)
我们将逐行分解此脚本,以便您了解它是如何工作的。最后,脚本将完全显示,因此您可以根据需要复制和粘贴它。
$TempFileLocation = "C:\Users\username\Appdata\Local\Temp\*"
前面有美元符号的任何东西都是变量名。把它想象成一个用来放贵重物品的钱包。钱包(Wallet)让我们想起了美元符号,贵重物品听起来很可变,所以我们也会记住这一点。$TempFileLocation的钱包或变量。等号告诉PowerShell在该变量中放入什么。
在这种情况下,我们将放置一个 Windows 临时文件位置C:\Users\username\AppData\Local\Temp\*。我们这样做有两个原因;它是一个始终可以安全删除文件的位置,我们将使用它来告诉PowerShell必须去哪里删除文件。
在该位置显示用户名的地方,将其换成您的用户名。这是您用于登录计算机的用户名。它末尾的星号 (*) 是通配符。它代表的是Temp文件夹中的所有内容,因为Temp文件夹中的所有内容都是临时的,我们要删除它。
位置周围的双引号也很重要。这告诉PowerShell里面有一个字符串。将(Think)字符串视为由字母和字符组成的字符串。如果是普通数字,我们不会使用引号。
$TempFile = Get-ChildItem $TempFileLocation -Recurse
我们正在制作另一个变量。这次我们将使用一个命令来想出一些东西来放入 $TempFile变量。
Get-ChildItem
关于Get-ChildItem( Get-ChildItem)之类的 cmdlet,您会注意到的另一件事是它完全可读。看看第一个单词是动词吗?Cmdlet(Cmdlets)都以动作词开头,因此您可以立即知道它在做什么。ChildItem是两个名词。
cmdlet 的第二部分总是会告诉我们PowerShell将应用该操作。ChildItem 表示父位置的所有子项。这就像说获取文件夹中的所有文件,文件是子文件,文件夹是父文件。
获取子项的 cmdlet 是什么?变量$TempFileLocation中的所有内容。PowerShell将转到我们之前放入 $ TempFileLocation的位置并获取那里的所有子项。然后,它将它们放入变量$TempFile中。
那么,-Recurse部分是怎么回事?这告诉Get-ChildItem遍历该位置的所有内容。不要直接在父文件夹中获取文件。如果该文件夹中有文件夹,也获取他们所有的孩子,以及他们的孩子等等。我们要把它们全部搞定。
$TempFileCount = ($TempFile).count
是的,我们正在创建名为$TempFileCount的第三个变量,我们将在该变量中放入一个数字。号码在哪里?好吧, ( $TempFile).count我们这个数字。您可能已经发现 .count部分将对我们刚刚存储在 $ TempFile 中的所有文件进行(.count)计数(TempFile)。
我们为什么这样做?主要是因为很高兴知道我们用脚本的其余部分清理了多少无用的文件,这样我们就可以知道它的有效性。
if($TempFileCount -eq 0)
现在我们正在设置一个条件语句。您可以看到它在询问“是否”。如果是什么?如果括号中的事物是真或假。括号很重要,否则 If 不知道要比较什么。在这里,它询问我们存储在$TempFileCount中的数字是否等于 0。
-eq是等于的简写。它是一种比较运算符。这就像告诉你的孩子,“如果你的房间很干净,很棒,我们会做点什么......”这句话是说如果存储在 $ TempFileCount中的数字 - 等于零接下来的事情。
{Write-Host "There are no files in the folder $TempFileLocation" -ForegroundColor Green}
$TempFileCount为零,就会发生这种情况。大括号很重要。如果 $ TempFileCount(TempFileCount)等于 0 ,它们会告诉PowerShell只执行它们内部的操作。
它将写入主机或屏幕,“C:\Users\username\Appdata\Local\Temp\* 文件夹中没有文件”。最后的参数 – ForegroundColor告诉PowerShell使文本变为绿色。这只是更容易与通常为红色的错误消息区分开来。
Else
你知道还有什么意思。这是检查您的孩子是否打扫房间的一部分,“您的房间最好打扫干净,否则...”。$TempFileCount不为零,就会发生这种情况。
{$TempFile | Remove-Item -WhatIf -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue}
这表示转到存储在$TempFile中的当前位置。它后面的垂直线称为管道。它的功能有点像现实生活中的管道,因为它告诉PowerShell将 $ TempFile的内容汇集到 cmdlet 中,就好像它是通过管道输送到洗衣机中的水一样。然后 cmdlet Remove-Item执行它所说的操作;它会删除该位置的任何内容。
-WhatIf参数在这个阶段非常重要。它告诉PowerShell运行命令,但只是尝试一下,不要删除任何内容。只要(Just)向我们展示如果我们真的这样做会发生什么。
这使您可以在不更改计算机上的任何内容的情况下测试命令。将 -WhatIf 保留在其中,直到您对脚本将执行您希望它执行的操作而不是其他操作感到满意为止。然后只需删除它,脚本就会完成它的工作。
参数-Confirm:$false阻止脚本询问您是否真的要删除文件。你知道-Recurse是做什么的。-Force意味着无论如何都要删除那个东西。-WarningAction设置为SilentlyContinue。
这可以防止脚本向您发出有关您正在删除的内容的警告。-ErrorAction设置为SilentlyContinue,这样如果过程中出现任何类型的错误,它就会继续运行。
现在我们在最后一行。
Write-Host "Cleared $TempFileCount files in the folder $TempFileLocation" -ForegroundColor Green}
就像Write-Host第一次做的一样,它会输出下面的句子,所以我们知道发生了什么。它会告诉我们从它刚刚处理的文件夹中删除了多少文件,并以绿色进行,以便于发现。
让我们一起看一下脚本:
$TempFileLocation = "C:\Users\guymcd\Appdata\Local\Temp\*"
$TempFile = Get-ChildItem $TempFileLocation -Recurse
$TempFileCount = ($TempFile).count
if($TempFileCount -eq "0") {
Write-Host "There are no files in the folder $TempFileLocation" - ForegroundColor Green
}
Else {
$TempFile | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
Write-Host "Cleared $TempFileCount files in the folder $TempFileLocation" -ForegroundColor Green
}
您可以将其复制并粘贴到您的PowerShell ISE中,并将其另存为delete-TemporaryFiles.ps1之类的内容。既然您已经了解了 cmdlet,那么您不妨坚持使用它们的命名约定。
如果代码由于某种原因不适合您,您还可以下载我们创建的 PowerShell 脚本并运行它。只需(Just)先将其解压缩以查看脚本文件。
每当您想运行此脚本时,只需右键单击它并选择Run with PowerShell。PowerShell控制台会弹出一两秒钟,而您的脚本会执行它的操作,然后如果没有错误就会消失。
在哪里可以了解更多 PowerShell?
这似乎很多!对于您的第一个PowerShell脚本来说,这是相当不错的。如果你已经做到了这一点,请为自己鼓掌。您今天学到了很多,但现在您想了解更多。那太棒了!
Internet上有很多资源可用于了解有关PowerShell的更多信息。我们的文章“通过命令行或 PowerShell 生成启动程序列表”(Generate a List of Startup Programs via Command Line or PowerShell)是一个很好的起点。然后查看这些其他资源:
Using PowerShell for Home Users – A Beginner’s Guide
Who doesn’t wish they could be a wizard and utter a few words to hаvе magical things hapрen? Well, wе’re not able to show you how tо be a wizard, but we can shоw you hоw to do a little computer magic.
If you’ve got a Windows computer with Windows 7 on it, you’ve got PowerShell. Also, if you have a computer with Windows 7 on it, please update it for security’s sake.
But this article isn’t just for Windows people. The latest version of PowerShell is free and can be installed and used on Mac’s and Linux computers.
That’s important because what you learn about PowerShell can be used on almost any computer now. Who knows? You might take this skill to the next level and venture into a career in Information Technology.
What is PowerShell?
The high-tech answer from Microsoft is that it is a, “…command-line shell designed especially for system administrators.” Sounds intimidating. But it’s not. Do you take care of your computer? Yes, then you’re the system administrator in your house.
Do you tell your computer what to do with clicks and keystrokes? Yes, so think of the command-line shell as just another window that you type things in to tell your computer what to do. You can do this.
PowerShell is like a programming language, but not as cryptic as most. It really reads a lot like regular English, which was something Microsoft strove for so that it could be picked up by non-programmers.
It’s a way of writing a few lines of commands, called a script, to make the Windows operating system do something that you want it to do. Then, you can save those lines in a file and run it with a click or schedule it to run periodically.
What Can You Do with PowerShell?
The high-level point of PowerShell is to be able to automate tasks, so you don’t have to waste your time doing mundane things repeatedly. For a professional Systems Administrator, that could be something like creating new users, generating passwords for them, and send an e-mail with the details to their new supervisor.
Manually done, with clicks and typing, that process can take 5 minutes to as much as an hour or more. With the right scripts, the Systems Administrator may not even have to do any part of that.
But you want to know what you can do with PowerShell at home. Pretty much anything that you don’t like doing again and again. Use it to free up space on your hard drive by deleting temporary and log files you don’t need.
Put a curfew on your kid’s computer. Rename or organize a bunch of files. That’s the beauty of PowerShell. Almost anything you can do on your computer, you can create a PowerShell script to automate and run with a click or on a schedule.
How Do I Use PowerShell?
The easiest way to work with PowerShell is in the PowerShell Integrated Scripting Environment (ISE). You can find it by clicking on Start and typing powershell ise into the search bar in Windows 10. You should see it as shown below.
For the first time that we use it, we’re going to run it as the Administrator. To do this, you must first have administrator rights on your computer. In your Start Menu, right-click on PowerShell ISE, then click on Run as Administrator.
You may get a User
Access Control (UAC) warning pop-up asking if you’re sure you want to do
this. Click Yes.
Now you’re looking at the PowerShell IDE. The top pane of the window (1) is the scripting pane. This is where you will write your script. The bottom pane of the window (2) is the console area. When you test your script, you’ll see the output in this pane.
This is also where you’ll see error messages and such that will help you fix and make your scripts better. The pane on the right-side of the window (3) is the command add-on. Think of it as a dictionary of all the PowerShell commands available to you.
PowerShell comes set to not run any script other than those
already a part of Windows. You’ll need to change it so that you can run your
own scripts.
In the scripting window, copy and paste the following:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
The Set-ExecutionPolicy part of it is called a cmdlet (pronounced commandlet). Cmdlets are powerful things. Think of them as short commands that you can give Windows, and Windows will go do a bunch of more complicated stuff to satisfy your command.
An analogy would be telling your kid to clean their room. Short and to the point. If your kid is well-versed in room cleaning, then they will go and make their bed, put their laundry in the basket, shelve their toys and books, and maybe even vacuum the floor. They understand that the cmdlet Clean-YourRoom meant all that.
At the top of the window, you’ll see a green arrowhead.
Click on that to run the command.
The -ExecutionPolicy part is telling Set-ExecutionPolicy what policy to set. It’s a parameter. It’s saying, “I want you to work within these guidelines and do specifically this. It tells it to use the specific policy of RemoteSigned.
The RemoteSigned policy states that PowerShell may not execute, or run, any script that was downloaded from the Internet unless it was signed by a trusted publisher.
In a roundabout way, it tells PowerShell that it’s fine to run any script created locally, because those don’t need to be signed by a remote trusted publisher. Now, your PowerShell script will be able to run any script you write on your computer.
Let’s look at a script to delete temporary files. It isn’t
as powerful or thorough as CCleaner, but CCleaner comes with its own set of
problems.
Use PowerShell to Create Space on Your Hard Drive
We’ll break down this script, line by line, so you can see
how it works. At the end, the script will be shown completely so you can copy
and paste it if you’d like.
$TempFileLocation = "C:\Users\username\Appdata\Local\Temp\*"
Anything with a dollar sign in front of it is a variable name. Think of it like a wallet to put valuable stuff in. Wallet reminds us of the dollar sign, valuables sounds like variable, so we’ll remember that too. We’re creating a wallet, or variable, named $TempFileLocation. The equal sign tells PowerShell what to put in that variable.
In this case, we’re putting in the location of a Windows’ temporary files location – C:\Users\username\AppData\Local\Temp\*. We’re doing this for two reasons; it’s a location that is always safe to delete files from, and we’re going to use it to tell PowerShell where it must go to delete files.
Where it says username in that
location, swap it for your user name. That’s the user name that you use to log
in to your computer. The asterisk (*) at the end of
it is a wild card. What it represents is everything in the folder Temp, because everything in the Temp folder is temporary
and we want to delete it.
The double-quotes around the location is important too. That
tells PowerShell that what’s in there is a string. Think of string as a string
of letters and characters. If it were ordinary numbers, we wouldn’t use the
quotes.
$TempFile = Get-ChildItem $TempFileLocation -Recurse
We’re making another variable. This time we’re going to use a command to come up with something to put in the $TempFile variable.
Get-ChildItem
Another thing you’ll notice about cmdlets like Get-ChildItem is that it is totally readable. See how the first word is a verb? Cmdlets all begin with action words, so you immediately know what it’s doing. ChildItem is two nouns.
The second part of the cmdlet is always going to tell us to what PowerShell will apply the action. ChildItem means all the children of a parent location. This is like saying get all the files that are in a folder, with files being the children and the folder being the parent.
What is the cmdlet getting the child items of? Everything in the variable $TempFileLocation. PowerShell is going to go to the location that we put in $TempFileLocation earlier and get all the child items that are there. Then, it will put them into the variable $TempFile.
So, what’s with the -Recurse part? That’s telling Get-ChildItem to go through everything in that location. Don’t just go get the files immediately inside the parent folder. If there are folders in that folder, get all their children too, and their children and so on. We’re going to get them all.
$TempFileCount = ($TempFile).count
Yes, we’re creating a third variable called $TempFileCount, and we’re going to put a number in that variable. Where’s the number? Well, ($TempFile).count is going to get us that number. You’ve probably figured out that the .count part is going to do the counting of all the files that we just stored in $TempFile.
Why did we do this? Mostly because it’s nice to know how many useless files we’re cleaning out with the rest of the script so we can tell how effective it was.
if($TempFileCount -eq 0)
Now we’re setting up a conditional statement. You can see that it’s asking ‘if’. If what? If the thing in the brackets is true or false. The brackets are important, otherwise the If doesn’t know what to compare. Here, it’s asking if the number we stored in $TempFileCount is equal to zero.
The -eq is the shorthand for equals. It’s a type of comparison operator. It’s like telling your kids, “If your room is clean, great, we’re going to do something…” This statement is saying if the number that was stored in $TempFileCount is -equal to zero do the next thing.
{Write-Host "There are no files in the folder $TempFileLocation" -ForegroundColor Green}
That’s the thing that will happen if $TempFileCount is zero. The curly brackets are important. They tell PowerShell to do only what is inside them if $TempFileCount equals zero.
It will write to the host, or the screen, “There are no files in the folder C:\Users\username\Appdata\Local\Temp\*”. The parameter at the end, –ForegroundColor tells PowerShell to make the text green. That just makes it easier to distinguish from an error message which is normally red.
Else
You know what else means. This is the, “Your room better be clean or else…” part of checking if your kid cleaned their room. It’s what will happen if $TempFileCount is not zero.
{$TempFile | Remove-Item -WhatIf -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue}
This says go to the current location stored in $TempFile. The vertical line after it is called a pipe. It does function kind of like a real-life pipe as it tells PowerShell to funnel the contents of $TempFile into the cmdlet, as though it was water being piped into a washing machine. Then the cmdlet Remove-Item does what it says; it removes whatever is at that location.
The -WhatIf parameter is very important at this stage. It tells PowerShell to run the command, but only try it out, don’t remove anything. Just show us what would happen if we really did this.
This allows you to test commands without changing anything on your computer. Leave the -WhatIf in there until you’re comfortable that the script is going to do what you want it to do and nothing else. Then just delete that out and the script will do its job.
The parameter -Confirm:$false stops the script from asking if you really want to delete the file. You know what -Recurse does. -Force means delete that thing no matter what. -WarningAction is set to SilentlyContinue.
This prevents the script from giving you warnings about what you’re deleting. -ErrorAction is set to SilentlyContinue so that if there’s any sort of error in the process, it just keeps chugging along.
Now we’re at the last line.
Write-Host "Cleared $TempFileCount files in the folder $TempFileLocation" -ForegroundColor Green}
Just like Write-Host did the first time, it’s going to output the following sentence, so we know what has happened. It will tell us how many files were deleted from the folder it just processed and do it in green to make it easy to spot.
Let’s look at the script altogether:
$TempFileLocation = "C:\Users\guymcd\Appdata\Local\Temp\*"
$TempFile = Get-ChildItem $TempFileLocation -Recurse
$TempFileCount = ($TempFile).count
if($TempFileCount -eq "0") {
Write-Host "There are no files in the folder $TempFileLocation" - ForegroundColor Green
}
Else {
$TempFile | Remove-Item -Confirm:$false -Recurse -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
Write-Host "Cleared $TempFileCount files in the folder $TempFileLocation" -ForegroundColor Green
}
You can copy and paste this into your PowerShell ISE and save it as something like delete-TemporaryFiles.ps1. You may as well stick with the naming convention of cmdlets now that you understand them.
If the code is not working for you for some reason, you can also download the PowerShell script we created and just run it. Just unzip it first to view the script file.
Whenever you want to run this script, just right-click on it and choose Run with PowerShell. A PowerShell console will pop up for a second or two, while your script does its thing, and then will disappear if there are no errors.
Where Can I Learn More PowerShell?
That seems like a lot! For your first PowerShell script it is a fair bit. If you’ve made it this far, applaud yourself. You’ve learned a lot today, but now you want to learn more. That’s great!
There are a lot of resources on the Internet for learning more about PowerShell. A good place to start is our article, “Generate a List of Startup Programs via Command Line or PowerShell”. Then check out these other resources: