I'm new to PS and Been messing with this for a while and I can't seem to get it right. I'm gathering information to create a log file name dynamically from reg keys and other variables and create the file if it's not present. I'm trying to create a scheduled task that would call up a script post reboot and writes to the log file a time and message that a reboot completed successfully. Then the scheduled task should remove itself as part of a cleanup function. I think the dynamic file name is the issue and that's why the scheduled task isn't completing and nothing is being written to my log file.
$Environment = `(Get-itemproperty -Path 'HKLM:\SOFTWARE\WOW6432Node\<software>\A180\12.2\Default\Account' )`
$ScriptType = 'Test'
$ScriptName = 'This might work'
$FolderPath = 'C:\Log\scripts\test'
If (!(Test-Path -Path "$($FolderPath)\$($Environment)_$($ScriptType)_$($ScriptName).log")) {
New-Item -ItemType File -Name $FileName -Force -Path "($FolderPath)\$($Environment)_$($ScriptType)_$($ScriptName).log"
}
Function Schedule-task
{
$Action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument -File "C:\My Folders\TaskScript.ps1"
$Trigger = New-JobTrigger -AtStartup -RandomDelay (New-TimeSpan -minutes 5)
$Principal = New-ScheduledTaskPrincipal -UserId "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName Post_Reboot_Script -Principal $Principal -Action $Action -Trigger $Trigger
}
Function Create-Script {
#Post restart script to confirm reboot
function Confirm
{
$Date_message = "$((get-date -format G)) Reboot complete"
Add-Content $Date_message -Path $FileName -Encoding Ascii
}
DoFirst -wait
#Remove script and scheduled task job from computer
function Cleanup
{
Remove-item "C:\My Folders\TaskScript.ps1" -force
Unregister-ScheduledTask -TaskName Post_Reboot_Script -confirm:$false
}
Cleanup