none
Error when invoking command to create scheduled task

    Question

  • I am writing some automation to update the IP of a server after it has been renamed.

    I am getting the following error message when the automation runs the invoke command to create the scheduled task:

    PSMessageDetails      : 
    OriginInfo            : newserver.test
    Exception             : System.Management.Automation.RemoteException: The 
                            system cannot find the file specified.
                            
    TargetObject          : PS_ScheduledTask
    CategoryInfo          : ObjectNotFound: 
                            (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) 
                            [Register-ScheduledTask], CimException
    FullyQualifiedErrorId : HRESULT 0x80070002,Register-ScheduledTask
    ErrorDetails          : 
    InvocationInfo        : System.Management.Automation.InvocationInfo
    ScriptStackTrace      : at <ScriptBlock>, 
                            \\automation-server.test\Logs\Migrate.Server.ps1: line 644
                            at <ScriptBlock>, <No file>: line 1
                            at <ScriptBlock>, <No file>: line 1
    PipelineIterationInfo : {}

    Here is the script block:

    #rename new server to old server
    Try{
    #scheduled task to re-IP new server
    Write-Log -Level INFO -Message "Creating scheduled task on $NewServer to update IP" -logfile $logfileloc
    try{
    Invoke-Command -ComputerName $NewServerFQDN -ScriptBlock{
        .([ScriptBlock]::Create($using:writelog))
        Write-Log -Level INFO -Message "Creating scheduled task on $Using:NewServer to update IP
        Network settings
        Adapter: $Using:Newserveradaptername
        IP: $Using:OldServerIP
        Gateway: $Using:Gateway
        " -logfile $Using:NewServerLogFile
    
        $TaskName = "Update IP for " + $Using:OldServer
        $Task = "C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe"
        $Argument1 = "netsh interface ipv4 set address name=`"$Using:Newserveradaptername`" static $Using:OldServerIP 255.255.254.0 $Using:Gateway"
        $WorkingDir = "%systemroot%\system32"
    
        Write-Log -Level INFO -Message "Task information for $Using:NewServer
        Task Name: $TaskName
        Task: $Task
        Argument: $Argument1
        Gateway: $Using:Gateway
        Working Directory: $WorkingDir
        " -logfile $Using:NewServerLogFile
    
        #Create scheduled task
        $ScheduledAction = New-ScheduledTaskAction –Execute $Task  -Argument $Argument1 -WorkingDirectory $WorkingDir
        $ScheduledTrigger = New-ScheduledTaskTrigger -Once -At (get-date).AddMinutes(10).ToString("HH:mm")
        $ScheduledSettings = New-ScheduledTaskSettingsSet -Compatibility V1 -DontStopOnIdleEnd -ExecutionTimeLimit (New-TimeSpan -Days 3) -Priority 5 -DeleteExpiredTaskAfter 3
        $ScheduledTask = New-ScheduledTask -Action $ScheduledAction -Trigger $ScheduledTrigger -Settings $ScheduledSettings
        Register-ScheduledTask -TaskName $TaskName -InputObject $ScheduledTask -User "NT AUTHORITY\SYSTEM"
        } -ErrorAction Stop
        }
        catch{
            $LastError = $Error[0] | select *
            Write-Log -Level ERROR "Could create scheduled task to set new IP on $NewServer
            $LastError" -logfile $logfileloc
        }
    Write-Log -Level INFO -Message "Rename $NewServer to $OldServer" -logfile $logfileloc
    Rename-Computer -ComputerName $NewServer -NewName $OldServer -Restart -Force -ErrorAction Stop -DomainCredential $creds
    }
    Catch{
    $LastError = $Error[0] | select *
    Write-Log -Level ERROR "Could not rename $NewServer to $OldServer
    $LastError" -logfile $logfileloc
    }

    The log file shows all the variables are correct and not null. I'm not calling any kind of file. Does anyone see any gotchas here? 

    Wednesday, February 6, 2019 4:10 PM

All replies

  • You need to give us the full error and not a text interpretation.  YUO are missing critical information.


    \_(ツ)_/

    Wednesday, February 6, 2019 5:21 PM
  • Hmm, ok. That is all that is provided when catching the error. Do you have a suggestion to get more verbose error logging?

    That is a copy/paste of the error with me omitting the server names.

    Wednesday, February 6, 2019 5:25 PM
  • You cannot use this:

    $WorkingDir = "%systemroot%\system32"

    You should not set the working directory to the Windows system.  You cannot use % in PowerShell.  The value will be null.

    $WorkingDir = "$env:windir\System32"


    \_(ツ)_/

    Wednesday, February 6, 2019 5:29 PM
  • Thanks jrv. I'll give that a whirl.
    Wednesday, February 6, 2019 5:43 PM
  • Did you write the code?  If so just return the error.

    Catch{
        $_
    }

    This will return the actual error and exit the script.


    \_(ツ)_/

    Wednesday, February 6, 2019 5:52 PM
  • ok, I removed the working directory entirely and it still failed. I got 1 more line in the error when I tried catching it.

    PSMessageDetails=; OriginInfo=server.test; Exception=System.Management.Automation.RemoteException: The system cannot find the file specified.
    ; TargetObject=PS_ScheduledTask; CategoryInfo=ObjectNotFound: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTask], CimException; FullyQualifiedErrorId=HRESULT 0x80070002,Register-ScheduledTask; ErrorDetails=; InvocationInfo=System.Management.Automation.InvocationInfo; ScriptStackTrace=at <ScriptBlock>, \\automation-server\Logs\Migrate.server.ps1: line 644
    at <ScriptBlock>, <No file>: line 1
    at <ScriptBlock>, <No file>: line 1; PipelineIterationInfo=System.Collections.ObjectModel.ReadOnlyCollection`1[System.Int32]


    Friday, February 8, 2019 3:48 PM
  • Can you tell us where you found the original code?

    The code looks very suspicious and appears to be written by someone with little knowledge of PowerShell. The colorization shows that the code is broken due to some bad closures.


    \_(ツ)_/

    Friday, February 8, 2019 7:37 PM
  • First use this to debug your code without all of the excess logging and visual noise:  When this works you can then add back the decorations a line at a time.

    $sb = {
        $TaskName = 'Update IP for ' + $Using:OldServer
        $Task = 'C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe'
        $Argument1 = 'netsh interface ipv4 set address name="{0}" static {1} 255.255.254.0 {2}' -f $Using:Newserveradaptername, $Using:OldServerIP, $Using:Gateway
        $WorkingDir = 'c:\temp'
        
        #Create scheduled task
        $ScheduledAction = New-ScheduledTaskAction –Execute $Task -Argument $Argument1 -WorkingDirectory $WorkingDir
        $ScheduledTrigger = New-ScheduledTaskTrigger -Once -At (get-date).AddMinutes(10).ToString("HH:mm")
        $ScheduledSettings = New-ScheduledTaskSettingsSet -Compatibility V1 -DontStopOnIdleEnd -ExecutionTimeLimit (New-TimeSpan -Days 3) -Priority 5 -DeleteExpiredTaskAfter 3
        $ScheduledTask = New-ScheduledTask -Action $ScheduledAction -Trigger $ScheduledTrigger -Settings $ScheduledSettings
        Register-ScheduledTask -TaskName $TaskName -InputObject $ScheduledTask -User 'NT AUTHORITY\SYSTEM'
    }
    Invoke-Command -ComputerName $NewServerFQDN -ScriptBlock $sb 
    



    \_(ツ)_/




    • Edited by jrv Friday, February 8, 2019 7:48 PM
    Friday, February 8, 2019 7:43 PM
  • This is how to catch errors correctly in a scriptblock.

    $sb = {
        $ErrorActionPreference = 'Stop'
        Try{
            $TaskName = 'Update IP for ' + $Using:OldServer
            $Task = 'C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe'
            $Argument1 = 'netsh interface ipv4 set address name="{0}" static {1} 255.255.254.0 {2}' -f $Using:Newserveradaptername, $Using:OldServerIP, $Using:Gateway
            $WorkingDir = 'c:\temp'
            
            #Create scheduled task
            $ScheduledAction = New-ScheduledTaskAction –Execute $Task -Argument $Argument1 -WorkingDirectory $WorkingDir
            $ScheduledTrigger = New-ScheduledTaskTrigger -Once -At (get-date).AddMinutes(10).ToString("HH:mm")
            $ScheduledSettings = New-ScheduledTaskSettingsSet -Compatibility V1 -DontStopOnIdleEnd -ExecutionTimeLimit (New-TimeSpan -Days 3) -Priority 5 -DeleteExpiredTaskAfter 3
            $ScheduledTask = New-ScheduledTask -Action $ScheduledAction -Trigger $ScheduledTrigger -Settings $ScheduledSettings
            Register-ScheduledTask -TaskName $TaskName -InputObject $ScheduledTask -User 'NT AUTHORITY\SYSTEM'
        }
        Catch{
            Throw
        }
    }
    Invoke-Command -ComputerName $NewServerFQDN -ScriptBlock $sb 
    


    \_(ツ)_/

    Friday, February 8, 2019 7:50 PM
  • I wrote this code. While I appreciate your replies, I do not appreciate being demeaned. The code works. I've tested in my lab. Once I execute in production something about the creation of the task does not come over properly.

    JRV, I think you need to work on your manners. You may have the answers but you could be a little nicer about your replies.

    Wednesday, February 13, 2019 6:42 PM
  • I wrote this code. While I appreciate your replies, I do not appreciate being demeaned. The code works. I've tested in my lab. Once I execute in production something about the creation of the task does not come over properly.

    JRV, I think you need to work on your manners. You may have the answers but you could be a little nicer about your replies.

    I think that was a legitimate question.  If you copied it I would have liked to see the original.

    You also have not tried any of the code I posted to try and get you n the right track. Why?

    Maybe when you don't like the message you want to shoot the messenger?  I am only trying to get you to learn how to debug this kind of issue.  If you know of a better way please tell us.

    If I have to answer questions like I am talking to a toddler I will become increasingly more annoyed  and less kindly.  I have no patience with adults who need to be treated like children.


    \_(ツ)_/

    Wednesday, February 13, 2019 6:51 PM