I am trying to get a script to self-delete after running, but I am having trouble figuring out the structure of the script. The script that I have works perfectly if I run it manually, but the issue is that I would then have to go back and manually remove the tasks that I've created.
I'm looking for some guidance on how to get this script to delete itself automatically after running (or +30 days).
Here is the current script in full:
$Trigger = New-ScheduledTaskTrigger -Once -At "01/11/2023 23:40:00"
$User = "domain\user"
$TaskName = $User,(Get-Date -Format "dd-MM-yyyy HH-mm-ss")
$command = @'
[System.Net.ServicePointManager]::SecurityProtocol =
[System.Net.SecurityProtocolType]::Tls12
$userName = 'myemail@website.com'
$passwordText = Get-Content C:\Users\User\Secure.txt
$securePwd = $passwordText | ConvertTo-SecureString
$credObject = New-Object System.Management.Automation.PSCredential -ArgumentList
$userName, $securePwd
connect-exchangeonline -Credential $credObject
Remove-MailboxFolderPermission -Identity usersemail@website.com:\Calendar -User
otherusersemail@website.com -Confirm:$false
$printConfig = (Get-ScheduledTask -TaskName Remove-Config).Triggers.StartBoundary
Write-Host Removed at $printConfig
'@
# Encode command to base-64
$commandBytes = [System.Text.Encoding]::Unicode.GetBytes( $command )
$commandBase64 = [Convert]::ToBase64String( $commandBytes )
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoExit -
EncodedCommand $commandBase64"
Register-ScheduledTask -TaskName "$TaskName" -Trigger $Trigger -User $User -Action
$Action -RunLevel Highest –Force
If I could also have any advice on how to call a variable from outside the here-string. I cannot change the single quote to double quotes, as this creates an error with the authentication.