PS script & scheduled task to move files
Hi All,
I need a little assistance with a powershell script that I want to run as a scheduled task. I need it to automatically move files of a certain age and need it to run everyday. This is the script that I have below:
I need to pass credentials to it because its copying over a network to a different location. How can I add credentials in this script so that it executes?
get-childitem -Path "D:\Backup" |
where-object {$_.LastWriteTime -lt (get-date).AddDays(-24)} |
move-item -Destination "y:\BAK" -Force
Thank You,
September 8th, 2015 8:02pm
Before providing the solution, I need to make it clear that it is extremely bad practice to embed credentials in scripts and I would strongly recommend you find a solution where the security principal that the script runs under has access to both systems.
That being said: you need to create a credential and pass the credential to Move-Item
$Credential = new-object system.management.automation.pscredential("DOMAIN\USER"),"PASSWORD")
move-item -Credential $Credential -Destination "y:\BAK" -Force
September 8th, 2015 8:20pm
Thanks but its saying that expressions are only allowed as the first element and also says this when I execute it.
September 8th, 2015 8:36pm
I did add my credentials and password just not in the screenshot for obvious reasons.
September 8th, 2015 8:36pm
you don't pipe the credential, the object is created on a separate line:
Your code should look like this:
$Credential = new-object system.management.automation.pscredential("DOMAIN\USER"),"PASSWORD")
get-childitem -Path "D:\Backup" | ?{$_.LastWriteTime -lt (get-date).AddDays(-24)} | move-item -Credential $Credential -Destination "y:\BAK" -Force
September 8th, 2015 8:51pm
Do not add credentials to a script that is to run as a task. It is not safe, portable or necessary. Just run the task under the target credentials when you create the task.
September 9th, 2015 1:54am
Do not add credentials to a script that is to run as a task. It is not safe, portable or necessary. Just run the task under the target credentials when you create
September 9th, 2015 2:01am
Do not add credentials to a script that is to run as a task. It is not safe, portable or necessary. Just run the task under the target credentials when you create the t
September 9th, 2015 2:18am
Kriss is the script supposed to prompt me for credentials? If so I wouldn't be able to schedule the task this way without a user being logged on.
Thanks
September 9th, 2015 7:44am
Kriss is the script supposed to prompt me for credentials? If so I wouldn't be able to schedule the task this way without a user being logged on.
Thanks
Use jrv's suggestion. No need for credentials if you schedule this properly.
September 9th, 2015 7:52am