Powershell中出现意外的令牌错误

jho*_*ard 4 powershell

我正在研究一个脚本,以更改Windows Server中的本地安全策略。当我在PowerShell提示符下自行运行这些命令时,它们可以正常工作。但是,当我运行脚本时,出现"Unexpected token 'PasswordComplexity' in expression or statement."错误。

问题似乎源于以下事实:脚本似乎没有执行secedit命令,因此这些get-content行没有要编辑的文件。

为什么secedit不运行?我尝试将secedit命令放在if语句之外,但得到的结果相同。

if ($win_ver -match "Server"){
    #export current secuirty policy
    secedit /export /cfg c:\new.cfg
    start-sleep -s 10
    #Disable Password Complexity
    ((get-content c:\new.cfg) -replace (‘PasswordComplexity = 1?, ‘PasswordComplexity = 0?)) | Out-File c:\new.cfg
    #Disable password expiration
    ((get-content c:\new.cfg) -replace (‘MaximumPasswordAge = 42?, ‘MaximumPasswordAge = -1?)) | Out-File c:\new.cfg
    #disable minmum password length
    ((get-content c:\new.cfg) -replace (‘MinimumPasswordLength = 6?, ‘MinimumPasswordLength = 1?)) | Out-File c:\new.cfg
    #import new security settings
    secedit /configure /db $env:windir\security\new.sdb /cfg c:\new.cfg /areas SECURITYPOLICY
}
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 5

PowerShell字符串文字必须用撇号括起来'...'

'string'
Run Code Online (Sandbox Code Playgroud)

或引号"..."

"string"
Run Code Online (Sandbox Code Playgroud)

因此,您使用的?字符无效,需要替换:

((get-content c:\new.cfg) -replace ('PasswordComplexity = 1', 'PasswordComplexity = 0')) | Out-File c:\new.cfg
Run Code Online (Sandbox Code Playgroud)

还要注意,用撇号括起来的字符串文字不会扩展变量。换句话说,这是:

$var = 123
Write-Host "My number: $var"
Run Code Online (Sandbox Code Playgroud)

将输出:

My number: 123
Run Code Online (Sandbox Code Playgroud)

像这样:

$var = 123
Write-Host 'My number: $var'
Run Code Online (Sandbox Code Playgroud)

将输出:

My number: $var
Run Code Online (Sandbox Code Playgroud)