PowserShell - Use CMD (schtasks) with Invoke-Command

ZodeQTN 20 Reputation points

Hello, i'm a beginner in PowerShell and i need your help !

I'm trying to create a script which has to do this :

  • Ask for computer names
  • Give a task to the computers list from an XML file

I call a function i made to ask the user all the computer names and i put them in $PCName.
I use invoke-command after this to run the schtasks using the cmd on all the devices.

<# Invoke-command to have access to other computers in the list. It calls the cmd of each PC and asks to run the schtasks command as Administrator. #>
Invoke-Command -ComputerName $PCName {`
 cmd /c 'schtasks /create /tn Insert_Name /xml "Insert_Path_from_server.xml"' }`
-Credential $Administrator`

All i can have is :

Access denied   + CategoryInfo : NotSpecified (Error:Access Denied : String) [], RemoteException   +FullyQualifiedError: NativeCommandError   +PSComputerName : Insert_PC_Name
   NotSpecified : (:String) [], RemoteException

I tried to replace the 'schtasks ...' with a simple 'ipconfig' and it worked. But i'm unable to access the task scheduler this way. I guess the problem comes from schtasks.

I'm running it on VMWare 16, script is on my Windows server 2019 with PS ISE and the computer i'm trying to to import the task on is a Windows 10.

If someone can help, it would be awesome ! I hope it's understandable !

A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,309 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 32,736 Reputation points

    Assuming that Insert_Path_from_server.xml contains a UNC path like \\server\share\filename.xml, then you are running into what is known as the double hop problem. The credentials that you used to authenticate to $PCName cannot be passed to \\server.

    There are many ways to accomplish scheduling the task, but without changing your script too much, this should work.

    $xml = get-content "Insert_Path_from_server.xml"       
    Invoke-Command -ComputerName $PCName {
    	$Filename = "C:\windows\temp\file.xml"          # save to the C: drive 
    	$using:xml | out-file $FileName                 # refernce the variable from the main script 
    	schtasks.exe /create /tn Insert_Name /xml $FileName 
    -Credential $Administrator



    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful