Share via

PowserShell - Use CMD (schtasks) with Invoke-Command

Anonymous
2023-11-24T14:20:51.0733333+00:00

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 !

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

MotoX80 37,696 Reputation points
2023-11-24T16:20:24.46+00:00

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

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-5.1

https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-5.1

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.