什么"。脚本"做?

时间:2015-05-28 10:36:59

标签: powershell

以下PowerShell代码行将做什么?

Set-Location D:\Utilities\AZ 
. D:\Utilities\AZ\Uti.ps1

我确信他第一行改变了路径但不确定第二行。

2 个答案:

答案 0 :(得分:4)

. C:\path\to\script.ps1部分称为“Dot Sourcing”。

当您运行没有点的脚本时,脚本的内容将在其自己的范围(Script范围)中执行,因此脚本内部定义的任何变量或函数在脚本之后都不会保留。完成了执行。

当您点源脚本(如您的示例中)时,脚本的内容将在调用者范围内执行,并且脚本中定义的函数即使在运行后也会保留。

来自about_Scripts帮助文件的引用:

SCRIPT SCOPE AND DOT SOURCING

    Each script runs in its own scope. The functions, variables, aliases, and
    drives that are created in the script exist only in the script scope. You
    cannot access these items or their values in the scope in which the
    script runs.

    To run a script in a different scope, you can specify a scope, such as
    Global or Local, or you can dot source the script.

    The dot sourcing feature lets you run a script in the current scope instead
    of in the script scope. When you run a script that is dot sourced, the 
    commands in the script run as though you had typed them at the command 
    prompt. The functions, variables, aliases, and drives that the script 
    creates are created in the scope in which you are working. After the script
    runs, you can use the created items and access their values in your session.

    To dot source a script, type a dot (.) and a space before the script path.

    For example:

        . C:\scripts\UtilityFunctions.ps1

    -or-

        . .\UtilityFunctions.ps1

答案 1 :(得分:3)

$m = new MongoClient(); echo "Connection to database successfully"; 将脚本的工作目录更改为给定文件夹。第二个语句dot-sources PowerShell脚本,即它加载文件的内容并在当前上下文中运行它(请参阅我链接到的帮助主题的 SCRIPT SCOPE AND DOT SOURCING 部分)

由于您说您无法运行该脚本,因此在点源时很可能会出现以下错误:

Set-Location

这意味着系统上PowerShell脚本的执行策略设置为File D:\Utilities\AZ\Uti.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details. At line:1 char:2 + . <<<< D:\Utilities\AZ\Uti.ps1 + CategoryInfo : NotSpecified: (:) [], PSSecurityException + FullyQualifiedErrorId : RuntimeException 。使用Restricted进行验证,并使用Get-ExecutionPolicy进行更改:

Set-ExecutionPolicy

或只是

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope User

如果您拥有管理权限。

如果Set-ExecutionPolicy RemoteSigned 失败,执行政策可能是使用组策略定义的,在这种情况下,您需要与管理员讨论该问题。

有关执行策略范围的更详细说明,请参阅here