Get-Child Item not working through task scheduler - powershell

I am trying to run this script through GPO deployed scheduled task:
$registryPath = 'HKLM:\Software\CC\PST_Discovery_Script\Already_Run'
if (!(Test-Path -Path $registryPath)) {
$dir = "c:\Users"
$ext = "pst"
Get-ChildItem "$dir" *$ext -r | Select-Object FullName,LastAccessTime,LastWriteTime,CreationTime,#{N='Owner';E={$_.GetAccessControl().Owner}}, #{Name="MegaBytes"; Expression={"{0:F2}" -f ($_.Length / 1MB)}}, #{N='Hostname';E={$env:computername}} | export-csv "c:\PST_Discovery.csv" -Append -NoTypeInformation
New-Item -Path HKLM:\Software\CC\PST_Discovery_Script -Name Already_Run –Force
}
It works fine if I run the script manually through the Powershell console/ISE, but not through a scheduled task.
If I run it through a scheduled task, I know the script is running because it reads the registry key, and if it doesn't exist it writes a registry key, but it does't actually run the get-childitem line or export a CSV.
The scheduled task shows up on the client, and it's running using a Domain Admin credentials (me)
EDIT: Sorry, my formatting for the code went all wrong, i think it should be fixed up now
kaspermoerch: Yes, it's a domain admin, and thus has full permissions over the file system
boxdog: I actually had it writing to a UNC share, but changed it to local computer because it wasn't working. I'll try some other combinations of output location and user.
TheIncorrigible: Originally it was system, but it wasn't working so I edited the pushed out scheduled task and am using my domain admin account.
Adam:
- Yes, scheduled task is created
- Yes, task runs script using following code: Powershell.exe -ExecutionPolicy Bypass \server1\share1\PST_Discovery_Script.ps1
- Yes, it runs using my DA creds
- Yes, the file isn't created, though it still writes the registry value
I've checked scheduled task, see my screenshot. I'm elevating the task scheduler and manually running the task.

Just to make sure I understand correctly.
The scheduled task is created.
The scheduled task runs a script containing the following code.
The scheduled task executes the script using your credentials.
Your account is in the Domain Admin group.
By "not working", the PST_Discovery.csv file isn't created.
Correct me if I misunderstood anything.
First: I'd verify the scheduled task is running in an elevated context (runas administrator). Even if the account executing the task is an administrator, the job needs to run in an elevated context.
Second: I'm curious how this works for you but not me. I've never seen a call to Select-Object quite like you've got. If I try to pipe an gci | Select-Object -Property #(...what you have...) | Export-Csv... I get an exception complaining about the FullName.
$registryPath = 'HKLM:\Software\CC\PST_Discovery_Script\Already_Run'
if (!(Test-Path -Path $registryPath)) {
$dir = 'c:\Users'
$ext = 'pst'
Get-ChildItem -Path $dir -Filter *$ext -Recurse |
Select-Object -Property #(
FullName
LastAccessTime
LastWriteTime
CreationTime
#{N = 'Owner'; E = {$_.GetAccessControl().Owner}}
#{Name = "MegaBytes"; Expression = {"{0:F2}" -f ($_.Length / 1MB)}}
#{N = 'Hostname'; E = {$env:computername}}
) |
Export-Csv -Path c:\PST_Discovery.csv -Append -NoTypeInformation
New-Item -Path HKLM:\Software\CC\PST_Discovery_Script -Name Already_Run –Force
}
You're 100% sure that works? I had to change that snippet to the following:
Select-Object -Property #(
, 'FullName'
, 'LastAccessTime'
, 'LastWriteTime'
, 'CreationTime'
#{N = 'Owner'; E = {$_.GetAccessControl().Owner}}
#{Name = "MegaBytes"; Expression = {"{0:F2}" -f ($_.Length / 1MB)}}
#{N = 'Hostname'; E = {$env:computername}}
I'm running Powershell 5 on Windows 10. I'm executing your example from the CLI.

I copied the code format you laid out, and it worked fine for me.
A quick and easy method to capture anything going wrong would be to change the error action preference to stop at the start of your script so that the process exits at the first error and any errors will flow back to the scheduled task's Last Run Result. From there you should be able to see the exception.
$ErrorActionPreference = 'Stop'
That should at least provide a starting point if you haven't already solved it. If that returns anything other than 0, then you know to build in some error handling with try/catch and perhaps an output log, to help you get to the bottom of it.

Related

Powershell script on VM as scheduled task

I wrote a simple script to move files that contain a specific substring in the file name from one folder to another.
$Source = Get-ChildItem -Path "C:\source" -Filter *.xlsm
$Target = "C:\target"
$substring = 'copy'
foreach ($file in $Source) {
if($file.Name -match $substring){
Move-Item -Path $file.FullName -Destination $Target -Force
}
}
I want to automate it on VM. It works fine when I'm running it manually and via task scheduler when I'm logged in VM, however when I switch to 'run whether logged on or logged off' in task scheduler (script properties) it won't work. I run it with following parameters:
-noprofile -executionpolicy unrestricted -noninteractive -file "path to my script"
Any ideas?
When the option "Run whether user is logged on or not" is selected, the scheduled task runs on a different session.
This means that it does not have access to the mapped network drives !.
So, you need to either map drives in your script or use the fully qualified name (i.e., \server name\share name)
More details here as well

"PowerShell on Target Machines" task fails with an error in TFS 2017\Azure Dev Ops

I am trying to run a PowerShell script present on one of the azure server using the "PowerShell on Target Machines" Task in my TFS build definition, but the task fails with the below error.
System.Management.Automation.RuntimeException: The running command
stopped because the preference variable "ErrorActionPreference" or
common parameter is set to Stop: The specified path, file name, or
both are too long. The fully qualified file name must be less than 260
characters, and the directory name must be less than 248 characters.
--->
I have copied the script in F drive but it still gives path too long error, not able to find any solution for the same.
Does anyone know what would be the reason?
Added script code as well for reference,
GetLatestDebugOutput.ps1
$DebugBuildOutput = "F:\Drops\econNextGen\SecurityScan\19.0"
$Dest = "F:\Drops\econNextGen\SecurityScan\Debug Build Output"
Remove-Item "$Dest\*" -Recurse -Force
#Code to Copy Common-App Debug Build
$Dir= $DebugBuildOutput + "\econNextGen-Common-App-Debug\"
$Latest = Get-ChildItem -Path $Dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$FolderPath= $Dir +$Latest.Name
Copy-Item -Path $FolderPath $Dest –Recurse -force
#Code to Copy Main-App Debug Build
$Dir= $DebugBuildOutput + "\econNextGen-MAIN-APP-Debug\"
$Latest = Get-ChildItem -Path $Dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$FolderPath= $Dir +$Latest.Name
Copy-Item -Path $FolderPath $Dest –Recurse -force
First suggest you directly RDP to remote target machine and check if you are able to run the same script in it. This will narrow down if the issue related to your tfs build definition and environment.
For environment, make sure you have met all prerequisites of this PowerShell on Target Machines task. And you have qualified powershell version installed.
Actually the error message is pretty straight forward, and so is the key point you should pay attention to: make sure you're not using paths that are too long or using an invalidly path. If apply for all folder and files.
Besides, try starting the build with diagnostics\debug enabled with system.debug=true and see if you can get any meaningful output for future troubleshooting.

Azure Devops - PowerShell task on self-hosted agent

I have an Azure Devops deployment pipeline setup which is building and I am able to deploy to a self hosted virtual machine with no issue.
I have the following powershell script that correctly clears down my destination directory leaving 2 folders that are not part of source control
Get-ChildItem -Path 'C:\inetpub\wwwroot\testDeploy\' -Recurse -exclude "pod","photos" |
Select -ExpandProperty FullName |
Where {$_ -notlike '*\pod\*' -and $_ -notlike '*\photos\*'} |
sort length -Descending |
Remove-Item -force
I have tried adding a "PowerShell Script" task but i'm don;t know how to get the PowerShell script in to a folder that the task can access i.e. $(System.DefaultWorkingDirectory). Can anyone advise how I should be either generating the file or where to store it in my repo that is then accessible by the self-hosted Windows agent
Agree with Shayki, you can create a powershell(.ps1) file in repos and paste your script in it to achieve that. And then, use powershell task to execute the script which in ps1 file.
But, as you said that you want it be maintained within the repos easily. Need made some change on your script:
Param(
[string]$RootPath,
[string]$File1,
[string]$File2,
[string]$NonLike1,
[string]$NonLike2
)
Get-ChildItem -Path $RootPath -Recurse -include $File1,$File2 |
Select -ExpandProperty FullName |
Where {$_ -notlike $NonLike1 -and $_ -notlike $NonLike2} |
sort length -Descending |
Remove-Item -Recurse -force
The first change is, you need to replace the hard code with variable. Pass the value with task, this is a good way to maintain your script.
The second which also the important change is add -Recurse after Remove-Item, or you will get the error showed below while the value of $RootPath is hard code, such as 'C:\Users\'.
Remove-Item : Windows PowerShell is in NonInteractive mode. Read and
Prompt functionality is not available.
And then, you can add task in your build pipeline. Add the Script path where the .ps1 file located and input the Arguments with the value:
If you want to access $(System.DefaultWorkingDirectory), pass it to $RootPath.
Hope my sample can help you achieve what you want.

PowerShell Script not running when set in the task scheduler

I'm attempting to create a task via powershell to delete some files older then 6 hours, if I execute the script from powershell there are no issues, if I try to execute from task scheduler nothing happens..
Call the Powershell.exe in my schedulded task:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Set this Parameters :
-NoProfile -ExecutionPolicy Bypass -Command -NonInteractive -File "C:\Scripts\DeleteFilesDiff3H.PS1"
What could be the problem of the task scheduler not launching my script?
Tried to aply some solutions provide to similar issues without success
$Path = "E:\MyPath"
$now = Get-Date
Get-Childitem * |
Where-Object { $_.LastWriteTime -le $now.AddHours(-6) } |
Remove-Item -Recurse -Force
I got this messages:
Task Scheduler started "{38dcd44b-4210-473b-921e-3cc1442ff03b}" instance of the "\Delete Files 3H" task for user "my user".
Task Engine "S-1-5-21-159114655-2248028564-2417230598-213599:My User:Interactive:LUA[2]" received a message from Task Scheduler service requesting to launch task "\Delete Files 3H" .
Task Scheduler launched "{38dcd44b-4210-473b-921e-3cc1442ff03b}" instance of task "\Delete Files 3H" due to a time trigger condition.
Task Scheduler successfully completed task "\Delete Files 3H" , instance "{618e6f44-b523-4c56-ae0b-04d3552391cc}" , action "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" with return code 0.
You don't make use of the defined variable $path so Get-ChildItem will never look there. Update your code to the following and check if this works for you:
$Path = "E:\MyPath"
$now = Get-Date
Get-Childitem -path $Path |
Where-Object { $_.LastWriteTime -le $now.AddHours(-6) } |
Remove-Item -Recurse -Force

SCCM - script still running

I've deployed powershell script that was writing information of user certificates on shared folder. I've deleted deployment but script is still running on computers and writing in that file. Do you know, how can I diagnose why scprit is still runing, or how can I end it? Attached script below.
Daniel
$report = #()
$certs = Get-ChildItem Cert:\CurrentUser\my -Recurse |
select #{n="Name"; e={$_.GetName()}}
$report += $env:computername+”;”+$env:username+”;”+$certs[0]+”;”+$certs[1]+”;”+$certs[2]
$report > \\server\certs.csv