官术网_书友最值得收藏!

Scripts

Scripts are simply files with a .ps1 file extension, which contain PowerShell code. It is possible to parameterize a script file in the same way that you would a function using a Param() statement at the beginning of the file. If we were to store the following code in a file called Get-PowerShellVersionMessage.ps1, it would be roughly equivalent to the Get-PowerShellVersionMessage function in the previous section:

param($name)
    $PowerShellVersion=$PSVersionTable.PSVersion
    return "We're using $PowerShellVersion, $name!"

A security feature of PowerShell is that it won't run a script in the current directory without specifically referring to the directory, so calling this script would look like this:

.\get-powershellversionmessage –name Mike

The following screenshot shows the aforementioned code being stored in a file:

And the output would be (on the computer I'm using): We're using PowerShell 4.0, Mike.

Note

Depending on your environment, you might not be able to run scripts until you change the execution policy. The execution policy dictates whether scripts are allowed to be executed, where those scripts can be located, and whether they need to be digitally signed. Typically, I use set-executionpolicy RemoteSigned to allow local scripts without requiring signatures. For more information about execution policies, refer to about_execution_policies.

It is also possible to define multiple functions in a script. However, when doing so, it is important to understand the concept of scope. When a script or function is executed, PowerShell creates a new memory area for definitions (for example, variables and functions) that are created during the execution. When the script or function exits, that memory is destroyed, thereby removing the new definitions. Executing a script with multiple functions will not export those functions into the current scope. Instead, the script executes in its own scope and defines the functions in that scope. When the script execution is finished, the newly created scope is exited, removing the function definitions. To overcome this situation, the dot-source operator was created. To dot-source a file means to run the file, without creating a new scope in which to run. If there was a script file with function definitions called myFuncs.ps1, dot-sourcing the file would use the following syntax:

. .\myFuncs.ps1

Note that there is a space after the first dot, and that since the script is in the current directory explicit use of the directory is required.

主站蜘蛛池模板: 新宁县| 江油市| 浦东新区| 丹棱县| 定日县| 涿鹿县| 昆明市| 丹江口市| 兰溪市| 天气| 砚山县| 青州市| 大丰市| 镇赉县| 梧州市| 黎川县| 临安市| 泸州市| 伊通| 封丘县| 富平县| 满城县| 明水县| 遵义市| 南开区| 信丰县| 荆门市| 温宿县| 和林格尔县| 拉孜县| 荃湾区| 唐山市| 象州县| 宜宾县| 许昌县| 昔阳县| 新竹县| 米易县| 东至县| 高青县| 岢岚县|