Search code examples
powershelluacnagiosaccess-denied

Trying to delete a file with Powershell script ran by a service but issues with uac


I'm having issues with a script that will delete a file on the C-Drive of a server. the script looks like this:

param(
[Parameter(Mandatory=$true)][string]$hostname
)

$StrFileName = "C:\Program Files\NSClient++\nsclient.log"
$LogLocal="c:\Nagios\naf_delete_nscp_log_file.log"

$Date = Get-Date -Format "yyyy-MM-dd hh:mm:ss"
"$date : NSClient logfile deletion requested on $hostname" | Out-File -filepath     $LogLocal -Append

If (Test-Path "$strFileName"){
    Remove-Item $strFileName -Force
$Date = Get-Date -Format "yyyy-MM-dd hh:mm:ss"
"$date : NSClient logfile deleted on $hostname" | Out-File -filepath $LogLocal -Append
}

The script is initiated from a Nagios quick action which will use nrpe to pass the host as parameter and make the nscp service, which runs as local system, run it. It works perfectly on servers that have no uac enabled, but I can't get it to work on servers with uac. I've tried numerous options, but none seem to work. Any tips or advice to get this working on servers with uac enabled is highly appreciated.

Thanks.

Willem


Solution

  • Inside your nsclient.ini file I think you just need to adjust either the wrapper for PowerShell or the definition for your script itself with -Verb RunAs. In the wrapper, for example, by default you have this:

    ps1 = cmd /c echo scripts\\%SCRIPT% %ARGS%; exit($lastexitcode) | powershell.exe -command -
    

    Which you could update with this

    ps1 = cmd /c echo scripts\\%SCRIPT% %ARGS%; exit($lastexitcode) | powershell.exe -command -Verb RunAs -
    

    Update from comments

    Would this definition work instead of using the wrapper

    naf_delete_nscp_log_file=powershell.exe -Verb RunAs -file scripts\naf_delete_nscp_log_file.ps1 "$ARG1$"