PowerShell脚本编写与控制流详解
1. 脚本编写基础
在PowerShell中,脚本是存储一系列命令的外部文件,只需在PowerShell控制台中输入一行代码,即可运行脚本。例如,要运行脚本,只需在控制台中输入其路径:
PS> C:\FolderPathToScript\script.ps1
Hello, I am in a script!
虽然在脚本中能做的事在控制台中也能完成,但使用脚本运行单个命令比手动输入数千条命令要方便得多。而且,如果需要修改代码或出现错误,重新输入命令会很麻烦。脚本编写能让你编写复杂、健壮的代码,但在开始编写脚本之前,需要更改一些PowerShell设置以确保能够运行脚本。
2. 设置执行策略
默认情况下,PowerShell不允许运行任何脚本。如果尝试在默认安装的PowerShell中运行外部脚本,会遇到如下错误:
PS> C:\PowerShellScript.ps1
C:\PowerShellScript.ps1: File C:\PowerShellScript.ps1 cannot be loaded because
running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ C:\PowerShellScript.ps1
+ ~~~~~~~~~~
超级会员免费看
订阅专栏 解锁全文
2065

被折叠的 条评论
为什么被折叠?



