1
votes

What am I trying to do?

Hi! I am writing a script that can accept 2 parameters, ComputerName and CheckWhatFile. The script will then access the computer (file server) specified by ComputerName and look for open file handles of CheckWhatFile.

The problem is the script needs to be executed by an administrative user. Our admins login as a non-privileged account. I want it to be as simple as clicking to run the script and only being prompted for the Get-Credentials box to enter there privileged account. I cannot use Invoke-Command unless you can find a way for it to not require having remote management turned on. The code below works when executed from a privileged PowerShell prompt that is started with runas /user: powershell.exe.

What I need help with

Help me find how to execute the 2 lines of code starting with netfile as a different user.

My code is:

param([string]$ComputerName = $null,[string]$CheckWhatFile = $null)
Import-Module ActiveDirectory

$Credentials = Get-Credential #Get Powerful Credentials

$netfile = [ADSI]"WinNT://$ComputerName/LanmanServer"
$netfile.Invoke("Resources") | foreach {
   try
   {
       $Id = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
       $ItemPath = $_.GetType().InvokeMember("Path", 'GetProperty', $null, $_, $null)
       $UserName = $_.GetType().InvokeMember("User", 'GetProperty', $null, $_, $null)
       $LockCount = $_.GetType().InvokeMember("LockCount", 'GetProperty', $null, $_, $null)

       if($ItemPath -eq $CheckWhatFile)
       {
            $Culprit = Get-ADUser -Filter {SamAccountName -eq $UserName} -Credential $Credentials
            Write-Host -ForegroundColor White -NoNewLine "Go Find "
            Write-Host -ForegroundColor Yellow -NoNewLine $Culprit.Name
            Write-Host -ForegroundColor White " and tell them to close the file!"
        }
    }
    catch
    {
    }
 }

Notes:

I have seen some examples with executing ADSI provider queries as a different user but they all relate to LDAP based queries not WinNT.

2
Using try..catch is pointless when you're not handling the caught errors. Just set $ErrorActionPreference = "SilentlyContinue" if you want the script to continue no matter what. - Ansgar Wiechers

2 Answers

0
votes

As it stands, the only way you're going to be able to do that is to have them RDP to the file server using the Admin credentials and run the script there. That's the only way they're going to get a powershell console to be able to see that output. Without powershell remoting enabled you can only get a local session, and that means either a local logon or RDP.

0
votes

Something like this might work:

$provider = "WinNT://$ComputerName/LanmanServer"
$cred     = Get-Credential

$netfile  = New-Object DirectoryServices.DirectoryEntry(
              $provider, $cred.UserName, $cred.GetNetworkCredential().Password
            )
$netfile.Invoke("Resources") | % {
  ...
}