Powershell 2.0 Script Works in cmd.exe but not Task Scheduler

I recently installed Powershell 2.0 on my SBS 2008 SP2 server and I think that it works well. When entering the server, both versions of Windows PowerShell (x86) and Windows Powershell have Get-ExecutionPolicy for RemoteSigned . >. Get-Host as Poweshell shows version as 2.0 .

The script is saved to C: \ Script \ Powershell \ on the server and is called TaskScheduler_Get_SFTP_Files.ps1

If I run from cmd.exe in C: \ the Powershell command C: \ Script \ Powershell \ TaskScheduler_Get_SFTP_Files.ps1 , Powershell then connects to FTP using various commands downloaded from PuTTY , renames the downloaded files and then saves them to its location. Throughout my session, I have various Write-Output commands when I run the script manually, which I can see on the cmd command line what is happening. This works fine with cmd.exe, and I see the destination directory with the downloaded files.

The Task Scheduler , on the other hand, seems to need sweet words of encouragement to do the job (currently besides my vocabulary). In the task scheduler, I created a task that has the following specification (copied from an XML export) and draws your attention to how I call Powershell with an argument:

<Principal id="Author"> <UserId>WOODBRIDGE\ADMIN</UserId> <LogonType>Password</LogonType> <RunLevel>HighestAvailable</RunLevel> </Principal> <Settings> <IdleSettings> <Duration>PT10M</Duration> <WaitTimeout>PT1H</WaitTimeout> <StopOnIdleEnd>true</StopOnIdleEnd> <RestartOnIdle>false</RestartOnIdle> </IdleSettings> <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> <AllowHardTerminate>true</AllowHardTerminate> <StartWhenAvailable>false</StartWhenAvailable> <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> <AllowStartOnDemand>true</AllowStartOnDemand> <Enabled>true</Enabled> <Hidden>false</Hidden> <RunOnlyIfIdle>false</RunOnlyIfIdle> <WakeToRun>true</WakeToRun> <ExecutionTimeLimit>PT4H</ExecutionTimeLimit> <Priority>7</Priority> </Settings> <Actions Context="Author"> <Exec> <Command>Powershell</Command> <Arguments>-NoProfile -File C:\Script\Powershell\TaskScheduler_Get_SFTP_Files.ps1</Arguments> </Exec> </Actions> 

When viewing the task history, one of the elements is EventID 201 , and the general comment is "Task Scheduler Task successfully completed" \ XXX \ YYYYYYYYYYYYYYYYYYYYY, instance "{23dee164- ea4b-4ed5-ba48-19f07bb83f3e}", action "C: \ Windows \ System32 \ WindowsPowerShell \ v1.0 \ Powershell.EXE "with return code 0. "

Any help would be appreciated?

+4
source share
3 answers

@nimizen will work, but in PowerShell 2.0 there is a slightly simpler way to run script files:

 -NoLogo -File C:\Script\Powershell\TaskScheduler_Get_SFTP_Files.ps1 

Regardless of whether you use the -NoProfile , whether your profile loads the modules or snapins that the script requires.

+1
source

It was strange that I did not quite understand. Thanks to all respondents for their contributions. I changed the arguments in the task scheduler to show -NoLogo -NoProfile -File ...

The only problem is that my Powershell sricpt would not execute a useful segment that created a new directory, uploaded FTP files and renamed them. At the beginning of the script, I had a dir> C: \ Temp \ Dir.txt command that would execute (it was just to see if the task scheduler really starts the task), however the actual part of intetest is for me (the bit that loaded and processed the information from FTP did not work.

Inside the task scheduler, I had to change the security settings to โ€œRun only at user loginโ€ with the user who is the Administrator for SBS 2008. If I try to save the task as โ€œRun whether the user is logged in or notโ€ and check the โ€œRun with highest privileges, "only the part that takes a copy of the directory is executed.

FYI, I only programmed in Powershell for a week, and itโ€™s not very convenient for me to work with regular expressions, so my code is pretty inefficient (can someone determine why the FTP part of the code does not start)? At the moment, I leave the task scheduler "Run only when the user logs in", at least in this way, the files are downloaded and processed.

Thanks to everyone. (Sorry for submitting my awful code, but for some it may be obvious why the part that goes beyond dir> C: \ Scripts \ Powershell \ dir.txt does not start when the Run Scheduler task is used or not, "and it can help people with a very simple inelegenat and insecure SFTP script to upload files?)

 # ----------------------------------------------------------------------------- clear dir > C:\Scripts\Powershell\dir.txt $ErrorActionPreference = 'SilentlyContinue' # Do not change the MM to mm as it will NOT return the month! [string]$TodayDate = Get-Date -Format "yyyyMMdd" [string]$DayName = Get-Date -Format "dddd" # ----------------------------------------------------------------------------- # Define the environment variables $ScriptPath = 'W:\IT\Utilities\PuTTY\' $DestFolder = 'W:\BBBB\Statements\' $BBBB_acc = ' myAccount@BBBB.com :outgoing/*.*' $BBBB_pwd = 'myPassword' $DoDelete = $false $Ext = @(".csv", ".pdf") $ExpectedFileNames = @("marginreport", "XXX14444", "XXX1cash", "XXX1money", "XXX1opnpos", "XXX1trades", "XXX1_an", "XXX1_ds", "XXX1_ep", "XXX1_ms") $ReplacedFileNames = @("Margin_MAC", "Call_Interest", "XXX_Cash", "XXX_Money", "XXX_Open", "XXX_Trades", "Margin_Analysis", "FFO", "XXX_EP", "Margin_Summary") $DoDownload = $true IF ($DayName -eq "Saturday") {$DoDownload = $false} IF ($DayName -eq "Sunday") {$DoDownload = $false} # ----------------------------------------------------------------------------- if ($DoDownload) { # Make sure the destination directories exist IF (!(Test-Path $DestFolder)){ New-Item -type directory -path $DestFolder # Write-Output ('Created target directory: ' + $DestFolder) } $TodaysDestFolder = $DestFolder + $TodayDate IF (!(Test-Path $TodaysDestFolder)){ New-Item -type directory -path $TodaysDestFolder # Write-Output ('Created todays target directory: ' + $TodaysDestFolder) } # ----------------------------------------------------------------------------- # SFTP todays Files # Old method of calling calling a batch file .\Download_BBBB_Outgoing.bat & ($ScriptPath + '\pscp.exe') -sftp -P 22 -pw $BBBB_pwd $BBBB_acc $DestFolder # Write-Output ("Finished Downloading Files") # ----------------------------------------------------------------------------- # Create the FTP Delete Script, Rename and Move the Files # The PuTTY batch files need to be ASCII, Powershell by default may write in UNICODE # Write-Output ('Creating Script File for FTP') $BBBB_Pattern = '\.(csv|pdf)' $BBBB_Script_FileName = "SFTP_BBBB_Delete_Files.txt" $BBBB_Script_FullFileName = $DestFolder + "\" + $BBBB_Script_FileName # Get-ChildItem $DestFolder -Recurse seems to traverse all subdirectories $Count = 0 "cd outgoing" | Out-File $BBBB_Script_FullFileName -encoding ASCII -force Get-ChildItem $DestFolder | Foreach-Object { if ($_.Name -match $BBBB_Pattern) { # Append the instruction to delete the file to the FTP script "del " + $_ | Out-File $BBBB_Script_FullFileName -encoding ASCII -append # Find the extension of the file $i = 0 while ((($_.name).ToLower()).IndexOf($Ext[$i]) -eq -1){ $i++} # See if there is a replacement name for the file $j = 0 while ((($_.name).ToLower()).IndexOf($ExpectedFileNames[$j]) -eq -1){ $j++} # Construct FileName $FTPDateStamp = ($_.name).substring(($_.name).length - 14, 14) $FTPDateStamp = $FTPDateStamp -replace("\.","") $IdxExt = (($_.Name).tolower()).IndexOf($Ext[$i]) if ($j -eq -1){ $NewName = ($_.name).substring(0,$IdxExt) + '_20' + $FTPDateStamp + $Ext[$i] } else { $NewName = $ReplacedFileNames[$j] + '_20' + $FTPDateStamp + $Ext[$i] } Rename-Item ($DestFolder + "\" + $_) -NewName $NewName Move-Item ($DestFolder + $NewName) $TodaysDestFolder $Count = $Count + 1 } } # ----------------------------------------------------------------------------- # Delete the downloaded files from the SFTP # PSFTP will terminate the batch if an error occurs. This can be changed with the -be switch # See 6.1.1 of the PuTTY release notes if ($DoDelete) { if ($Count -gt 0) { # Write-Output ('Deleting the downloaded files from SFTP account') & ($ScriptPath + '\psftp.exe') -batch myAccount@BBBB.com -pw $BBBB_pwd -P 22 -b $BBBB_Script_FullFileName } } Remove-Item $BBBB_Script_FullFileName $ErrorActionPreference = 'Continue' # Write-Output ('Script finished to download from BBBB SFTP account') } 
+1
source

Try changing the command arguments as follows:

 -noprofile -nologo -command "&{C:\Script\Powershell\TaskScheduler_Get_SFTP_Files.ps1}" 
0
source

All Articles