# Powershell Script execution using Schdule tasks

**URL:** <https://forums.powershell.org/t/powershell-script-execution-using-schdule-tasks/19539>\
**Category:** PowerShell Help\
**Created:** [June 8, 2022, 6:46pm UTC](https://forums.powershell.org/t/powershell-script-execution-using-schdule-tasks/19539 "2022-06-08T18:46:06Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Daaku](https://avatars.discourse-cdn.com/v4/letter/d/9e8a1a/32.png) [@Daaku](https://forums.powershell.org/u/Daaku)\
**Post date:** [June 8, 2022, 6:46pm UTC](https://forums.powershell.org/t/powershell-script-execution-using-schdule-tasks/19539/1 "2022-06-08T18:46:06Z")

</div>

I need to go over a list of web services and query them individually and pull the details and store it into the database, I designed the code in the following way

Script 1 connects to the SNOW and pulls in the list of web servcies that i need to connect and loops them through the list and triggers a “Start-ThreadJob” with the service name as an argument  
Scipt 2 connects to that specific web service (received as an argument) and connects to it and pull in the data and reports it to the database.  
When i run the script 1 manually The script 1 is successfully calling all the required web services and the data is being reported to the database, however when i try to call the script 1 using the windows schdule task, The script 1 executes but the script 2 is not being triggered. do i need to set

Any specific excution policies  
Scope  
Any inputs is appreciated, Here is an example for how the script 1 and 2 looks

Script 1

#Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted  
##############################################################################################################  
#Function Name: ErrorHandler  
#Inputs: Error Type(Info, Warning or Error), Error String  
#Output: None  
#Description: If the error type is ‘Error’ then captures the last known exceptions reported and appends to the file.

# If the error type is something else then the error message is appended to the log file.

##############################################################################################################  
Function ErrorHandler ($errType, $ErrorString)  
{  
$timestamp = Get-Date -Format o  
if ($errType -eq ‘Error’)  
{  
$errorstr = $timestamp + ’ : ’ + $errType + ’ - ’ + $ErrorString + $Error[0].Exception  
}  
else  
{  
$errorstr = $timestamp + ’ : ’ + $errType + ’ - ’ + $ErrorString  
}  
$errcounter = 0  
$maxerrcounter = 5  
do  
{  
try  
{  
$errorstr | Out-File $ErrFile -Append  
break  
}  
catch  
{  
Start-Sleep 10  
$errcounter++  
}  
}while ($errcounter -le $maxerrcounter)  
}

##############################################################################################################  
#Initialize Variable  
##############################################################################################################  
#Key file path  
$CredFilePath = "E:\WIS\MonitorConfiguration\Schduled\Stage\creds"  
#Error file name  
$ErrFile = ‘C:\MonitorReportLogs\Sitescope\_Config\_Pull.log’  
$authorization = $null  
#SNOW API server fqdn  
$SnowFQDNhost = “”  
###################################  
#Build Snow API authorization header  
###################################  
$user= Get-Content $CredFilePath’SNOW\_User.txt’  
$KeyFile = $CredFilePath+‘AES.key’  
$key = Get-Content $KeyFile  
$EncryptedPW = Get-Content $CredFilePath’SNOW\_Pass.txt’ | ConvertTo-SecureString -Key $key  
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($EncryptedPW)  
$pass = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)  
$pair = “$($user):$($pass)”  
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))  
$authorization = “Basic $encodedCreds”

#SNOW API authorization Header assignment  
$Headers = @{  
Authorization = $authorization  
}

###################################  
#Query SNOW for the list of sitescope instances  
###################################  
$snowsysurl=“https://” + $SnowFQDNhost + “/api/now/table/u\_cmdb\_relationship\_report?sysparm\_query=u\_service.name=BSM SiteScope - Production&sysparm\_fields=u\_hardware.fqdn”  
try  
{  
$info=Invoke-WebRequest -Uri $snowsysurl -Headers $Headers  
}  
catch  
{  
$errStr = "SNOW Sitescope server list API request for the URL: “+ $snowsysurl +” failed - "  
ErrorHandler ‘Error’ $errStr  
}

###################################  
#Process each sitescope instance monitor data  
###################################  
If($info -eq $null){  
$errStr = “Unhandled Exception parsing data for " + $SnowFQDNhost + " exiting Script.”  
ErrorHandler ‘Error’ $errStr  
Exit  
}  
else  
{  
#convert the JSON response to PS Custom data object dictionary  
$snowContent = $info | ConvertFrom-Json  
#Query each sitescope on the list and process the configuration data  
$jobCounter = 0  
if (($snowContent.result.‘u\_hardware.fqdn’ -ne $null) -and ($snowContent.result.‘u\_hardware.fqdn’ -ne ‘’))  
{  
foreach($obj in $snowContent.result.‘u\_hardware.fqdn’)  
{  
if (($obj -ne $null) -and ($obj -ne ‘’))  
{  
Start-ThreadJob -ScriptBlock {param($hostname) E:\WIS\MonitorConfiguration\Schduled\Stage\SIS\_Config\_DB\_Push.ps1 $hostname}`  
-ArgumentList ($obj) -ThrottleLimit 10 -Name $obj  
$errStr = "Triggered the script for server : "+ $obj  
ErrorHandler ‘Info’ $errStr  
}  
}  
}  
else  
{  
$errStr = “SNOW Sitescope server list API request for the URL: “+ $snowsysurl +” returned 0 records.”  
ErrorHandler ‘Error’ $errStr  
}  
}

###################################  
#Garbage Collection  
###################################  
$info = $null  
$snowContent = $null  
Script 2: (Limited Version)

#Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted  
##############################################################################################################  
#Function Name: ErrorHandler  
#Inputs: Error Type(Info, Warning or Error), Error String  
#Output: None  
#Description: If the error type is ‘Error’ then captures the last known exceptions reported and appends to the file.

# If the error type is something else then the error message is appended to the log file.

##############################################################################################################  
Function ErrorHandler ($errType, $ErrorString)  
{  
$timestamp = Get-Date -Format o  
if ($errType -eq ‘Error’)  
{  
$errorstr = $timestamp + ’ : ’ + $errType + ’ - Server Name: ’ + $SiSServerName + ’ - ’ + $ErrorString + $Error[0].Exception  
}  
else  
{  
$errorstr = $timestamp + ’ : ’ + $errType + ’ - Server Name: ’ + $SiSServerName + ’ - ’ + $ErrorString  
}  
$errcounter = 0  
$maxerrcounter = 5  
do  
{  
try  
{  
$errorstr | Out-File $ErrFile -Append  
break  
}  
catch  
{  
Start-Sleep 10  
$errcounter++  
}  
}while ($errcounter -le $maxerrcounter)  
}

$obj = $args[0]  
#Error file name  
$ErrFile = ‘C:\MonitorReportLogs\Sitescope\_Config\_Pull.log’  
$errStr = "Start processing data for " + $obj  
ErrorHandler ‘Info’ $errStr

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [June 8, 2022, 7:10pm UTC](https://forums.powershell.org/t/powershell-script-execution-using-schdule-tasks/19539/2 "2022-06-08T19:10:30Z")

</div>

Before we proceed - please go back, edit your question and fix the formatting of your code.

To post code, sample data, console output or error messages please format it as code using the _preformatted text_ button ( **\</\>** ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

[How to format code in PowerShell.org](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/b/bee50c628238f2c076c0504efb6b15f2fb11f002.gif) \<---- Click 👆🏽 😉

---

<div class="post-metadata">

**Author:** ![tonyd](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/tonyd/32/1041_2.png) [@tonyd](https://forums.powershell.org/u/tonyd)\
**Post date:** [June 8, 2022, 10:02pm UTC](https://forums.powershell.org/t/powershell-script-execution-using-schdule-tasks/19539/3 "2022-06-08T22:02:28Z")

</div>

> [@Daaku](#):
>
> E:\WIS\MonitorConfiguration\Schduled\Stage\SIS\_Config\_DB\_Push.ps1 $hostname}`

If the E: drive is mapped, does the user defined in the task running the script have the proper permissions?

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:17pm UTC](https://forums.powershell.org/t/powershell-script-execution-using-schdule-tasks/19539/4 "2024-05-16T20:17:54Z")

</div>

Closed on May 16, 2024, 8:17pm UTC


