如果那么Else打破了我的剧本

时间:2014-05-07 18:14:24

标签: windows powershell scheduled-tasks

目前我有这段代码 -

Set-ExecutionPolicy Unrestricted
$name = (Get-WmiObject win32_bios).SerialNumber.Trim()
$oldname = (Get-WmiObject win32_computersystem).Name.Trim()
IF ($oldname -eq $name){Exit}
Else{ Rename-computer -ComputerName $oldname  -NewName "$name" -force
Start-Sleep -s 5

Restart-Computer}

我已将其设置为在登录时作为计划任务运行,并且没有If Else它完美运行但是我不想让它在每次用户登录时运行,因为它只是一个重启的循环。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我会建议一些改变:

  1. Set-ExecutionPolicy是不必要的,因为如果机器已经开始处理脚本,那么executionpolicy不是问题。所以请删除它,并在powershell.exe - 调用中指定它,例如:powershell.exe -executionpolicy unrestricted

  2. 使用if($oldname -ne $name) { rename-computer .... },以便删除其他部分。更清洁

  3. 尝试运行下面修改后的脚本,然后使用scriptlog.txt - 文件中的输出进行报告。

    $logpath = "c:\scriptlog.txt"
    
    $name = (Get-WmiObject win32_bios).SerialNumber.Trim()
    $oldname = (Get-WmiObject win32_computersystem).Name.Trim()
    
    "NewName is '$name'" | Out-File $logpath -Append
    "OldName is '$oldname'" | Out-File $logpath -Append
    
    IF ($oldname -ne $name){
        "If-test TRUE" | Out-File $logpath -Append
    
        Rename-computer -ComputerName $oldname  -NewName $name -Force
        Start-Sleep -s 5
    
        Restart-Computer
    } else { #I've added the else-part just because of logging.
        "IF-test FALSE" | Out-File $logpath -Append
    }
    
相关问题