Farziddin Doniyorov
Farziddin Doniyorov

Reputation: 11

Can not run ps1 as script

i wanna run the following script as ps1, if i copy and paste it on powershell as admin, it works fine, but as ps1 it does not show any error but does not function either: Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force

# We will write events to the Windows Application log with source name of CheckUSB
If (-not [System.Diagnostics.Eventlog]::SourceExists('CheckHard')) {
    # Event log source does not exist, so we create it
    New-EventLog -LogName Application -Source 'CheckHard'
}

# Unregister this event only
Unregister-Event RemovableHardDetection -Force

# Define the WMI query
$query = 'SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA ''Win32_DiskDrive'''

# Define the action to be performed when the event is triggered
$action = {
    $strUSBSerialFilename = 'C:\usbcontrol\usb_serial.json'
    $strClass = $eventArgs.NewEvent.__CLASS
    $strPNPdeviceID = $eventArgs.NewEvent.TargetInstance.PNPDeviceID
    $arraySplitPNPdeviceID = $strPNPdeviceID.split('\')
    $strConnectedUSBSerial = $arraySplitPNPdeviceID[-1]
    $strlogfile = 'C:\usbcontrol\usbcontrol.log'
    $strdatetime = Get-Date
    $strdatetime = $strdatetime.GetDateTimeFormats()[19]

    function Read-approved-USB($strFileWithPath) {
        if (Test-Path $strFileWithPath) {
            $tempObj = $null 
            try {   
                $tempObj = Get-Content -Raw -Path $strFileWithPath | ConvertFrom-Json
                Write-Output $tempObj # Return PowerShell representation of JSON file back. Must have this line.  
            }
            catch {
                $ErrorMessage = $_.Exception.Message
                $FailedItem = $_.Exception.ItemName
                $strMessageToSend = " [$strdatetime] Error: $ErrorMessage for $FailedItem"
                Write-Host " $strMessageToSend "
                Write-Output " $strMessageToSend " | Out-File $strlogfile -Append
                Write-Error $StrMessageToSend -ErrorAction Stop
            }
        }
    }

    function Check-for-approved-USB($strSerialFileName, $strConUSBSerial) {
        $IntReturnValue = 0
        $objSerials = Read-approved-USB $strSerialFileName
        $objSerials.ValidSerialNumbers | foreach {
            $ApprovedSN = $_
            if ($ApprovedSN.USBSerial -eq $strConUSBSerial) {        
                # The USB serial is on the approved list, indicate that by setting IntReturnValue to 1
                $IntReturnValue = 1
                $strMessageToSend = "USB [$strdatetime] JSON value: " + $ApprovedSN.USBSerial + " Equals " +  $USBSerialNumber
                Write-Host "$strMessageToSend"
                Write-Output "$strMessageToSend " | Out-File $strlogfile -Append
            }
            else {
                $strMessageToSend = "USB  [$strdatetime] JSON value: " + $ApprovedSN.USBSerial + " Not equals " +  $USBSerialNumber
                Write-Host " $strMessageToSend"  
                Write-Output "$strMessageToSend " | Out-File $strlogfile -Append
            }
        }
        Write-Output $IntReturnValue
    }

    # Switch based on event class
    switch ($strClass) {
        __InstanceCreationEvent {
            $intApprovedUSB = 0
            Disable-PnpDevice -InstanceId $strPNPdeviceID -Confirm:$false
            $intApprovedUSB = Check-for-approved-USB $strUSBSerialFilename $strConnectedUSBSerial
            $strMessageToSend = "HARD DISK [$strdatetime] Insertion event for $strPNPdeviceID. Check if approved returned: $intApprovedUSB"
            Write-Host $strMessageToSend
            Write-Output " $strMessageToSend " | Out-File $strlogfile -Append
            if ($intApprovedUSB -eq 1) {
                $strMessageToSend = "USB [$strdatetime] Inserted, device id: $strPNPdeviceID with serial: $strConnectedUSBSerial on approved list."
                Write-Host $strMessageToSend 
                Write-Output " $strMessageToSend " | Out-File $strlogfile -Append
                Enable-PnpDevice -InstanceId $strPNPdeviceID -Confirm:$false
            }
            else {
                $strMessageToSend = "HARD DISK [$strdatetime] Inserted, device id: $strPNPdeviceID with serial: $strConnectedUSBSerial not on approved list."
                Write-Host $strMessageToSend
                Write-Output "$strMessageToSend " | Out-File $strlogfile -Append
            }
        }

        __InstanceDeletionEvent {
            $strMessageToSend = "USB [$strdatetime] Removed, device id: $strPNPdeviceID with serial: $strConnectedUSBSerial"
            Write-Host $strMessageToSend
            Write-Output " $strMessageToSend " | Out-File $strlogfile -Append
        }

        __InstanceModificationEvent {
            $intApprovedUSB = 0
            Disable-PnpDevice -InstanceId $strPNPdeviceID -Confirm:$false
            $intApprovedUSB = Check-for-approved-USB $strUSBSerialFilename $strConnectedUSBSerial
            $strMessageToSend = "USB [$strdatetime] Modification event for $strPNPdeviceID. Check if approved returned: $intApprovedUSB"
            Write-Host $strMessageToSend
            Write-Output " $strMessageToSend " | Out-File $strlogfile -Append
            if ($intApprovedUSB -eq 1) {
                $strMessageToSend = "USB [$strdatetime] Inserted, device id: $strPNPdeviceID with serial: $strConnectedUSBSerial on approved list."
                Write-Host $strMessageToSend 
                Write-Output " $strMessageToSend " | Out-File $strlogfile -Append
                Enable-PnpDevice -InstanceId $strPNPdeviceID -Confirm:$false
            }
            else {
                $strMessageToSend = "USB [$strdatetime] Inserted, device id: $strPNPdeviceID with serial: $strConnectedUSBSerial not on approved list."
                Write-Host $strMessageToSend
                Write-Output " $strMessageToSend " | Out-File $strlogfile -Append
            }
        }
    }
}

# Register the WMI event
Register-WmiEvent -Query $query -SourceIdentifier RemovableHardDetection -Action $action -ComputerName $ENV:COMPUTERNAME

it is a code to detect Hard Disk insertion and after insertion it disables it if its id is not found from white-list, when i copy and paste it to powershell it works totally fine, but when i close the console, it stops working. I want it keep running untill poweroff, coz i am gonna execute it on every start-up with task-scheduler. Please help me with it, i have been trying for almost a week now

Upvotes: 0

Views: 48

Answers (0)

Related Questions