【问题标题】:Block of code prevents script from running, but runs interactively代码块阻止脚本运行,但以交互方式运行
【发布时间】:2016-09-10 04:28:26
【问题描述】:

我有一个作为计划任务运行的脚本,该脚本在定义 $As 的行上出现意外令牌错误而失败。如果我删除代码,脚本会正常运行。如果我将整个脚本(包括有问题的部分)粘贴到 PowerShell 窗口中,一切都会按预期运行。

我假设这是一个我没有遇到过的简单问题,但我无法弄清楚它有什么问题,如果有经验的眼睛会很感激。

这是在 Server 2012R2 上运行的,带有 PS 5.0.117,但也发生在版本 4 下。

# Sanitize $UserLogon
$Garbage = "[?\' ]",''
$As = '[?ÀÁÂÃÄÅÆàáâãäåæ]','a'
$Cs = '[?Çç]','c'
$Es = '[?ÈÉÊËèéêë]','e'
$Is = '[?ÌÍÎÏìíîï]','i'
$Ns = '[?Ññ]','n'
$Os = '[?ÒÓÔÕÖØðòóôõöø]','o'
$Ss = '[?ß]','s'
$Us = '[?ÙÚÛÜùúûü]','u'
$Thorns = '[?Þþ]','th'

$TextReplacers = $Garbage, $As, $Cs, $Es, $Is, $Ns, $Os, $Ss, $Us, $Thorns

foreach ($Replacement in $TextReplacers) {
    $UserLogon = $UserLogon -replace $Replacement
    }

我收到的确切错误是:

At C:\Scripts\Onboarding\CreateUserAccount0.ps1:121 char:17
+     $As = '[?ÀÃÂÃÄÅÆàáâãäåæ]','a'
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Unexpected token 'ÃÄÅÆàáâãäåæ]','a'
    $Cs = '[?Çç]','c'
    $Es = '[?ÈÉÊËèéêë]','e'
    $Is = '[?ÃŒÃÃŽÃìíîï]','i'
    $Ns = '[?Ññ]','n'
    $Os = '[?ÒÓÔÕÖØðòóôõöø]','o'
    $Ss = '[?ß]','s'
    $Us = '[?ÙÚÛÜùúûü]','u'
    $Thorns = '[?Þþ]','th'

    $TextReplacers = $Garbage, $As, $Cs, $Es, $Is, $Ns, $Os, $Ss, $Us, $Thorns

    foreach ($Replacement in $TextReplacers) {
        $UserLogon = $UserLogon -replace $Replacement
        }
# Check if AD user already exists.
$UserExists = Get-ADUser -Filter {SamAccountName -eq $UserLogon}
if ($UserExists -ne $Null){
    $email = new-object Net.Mail.SMTPClient($mailServer)
    $err += "$UserLogon' in expression or statement.

如果我注释掉 $As,它会发生在 $Ns 和 $Os 上。如果我注释掉 $As、$Ns 和 $Os,它运行良好。

【问题讨论】:

    标签: powershell powershell-4.0 powershell-5.0


    【解决方案1】:

    PowerShell 可以从脚本文件 BOM 中检测以下编码:UTF-8、UTF-16(LE 和 BE)和 UTF-32(LE 和 BE)。如果 BOM 不存在,则 PowerShell 将 Encoding.Default 用于脚本文件。因此,您的 UTF-8 脚本文件应包含 BOM,以便识别 UTF-8。

    在您的情况下,由于 PowerShell 解释以下所有字符而发生错误:'‘’‚‛ — 作为单引号字符。因此,当您的脚本文件以不正确的编码读取时,字符串文字的某些部分会获得特殊含义并导致语法违规。

    $As = '[?ÀÃÂÃÄÅÆà áâãäåæ]','a'
                 ^
    $Ns = '[?Ññ]','n'
              ^
    $Os = '[?ÒÓÔÕÖØðòóôõöø]','o'
              ^
    

    【讨论】:

    • 谢谢。使用 BOM 重新保存文件修复了此问题。感谢您提供有关问题所在的背景详细信息,而不仅仅是解决问题。
    猜你喜欢
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多