简体   繁体   中英

How to properly call Powershell script from Batch script (fix a bug)

My script in batch main.bat should call other script in Powershell 07-PermissionsChecking.ps1 , but it opens the mouse properties instead and I have no idea why it does that.

When I execute 07-PermissionsChecking.ps1 directly from Powershell, it works fine as expected. This code tries to open folders in shared-drive, and tries to create files in order to verify read & write access permissions for the user.

Can someone help to make it work calling from main.bat ?

EDIT: After I rename a function previously named as "main" to "myfunction" the error changed to:

"-myfunction : The term 'myfunction' is not recognizer as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

main.bat :

Powershell -command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser"
Powershell -noexit "& ""Y:\02 - Installations\Batch files\07-PermissionsChecking.ps1"""

07-PermissionsChecking.ps1 :

clear 
$error.Clear()

$AvailableProjectsPath = "\\Abrrec01fscp030\swc$\HIL\Available Projects\AccessCtrl"
$WorkspacePath = "\\Abrrec01fscp030\swc$\HIL\Available Projects\Workspace\AccessCtrl"
$WorkInProgressPath = "\\Abrrec01fscp030\swc$\HIL\Work In Progress\AccessCtrl"

$currentDate = (Get-Date).ToString('MM/dd/yyyy')
$currentTime = (Get-Date).ToString('HH:mm:sstt')

$text = ""

myfunction

function myfunction{
    if (Test-Connection -ComputerName Abrrec01fscp030 -Quiet -Count 1){

        CheckAccessStatus $AvailableProjectsPath
        CheckAccessStatus $WorkspacePath
        CheckAccessStatus $WorkInProgressPath

    }
    else
    {
        Write-Host "Make sure you are connected to FIATAUTO network"
    }
}

function CheckAccessStatus{

    Param ([string]$path)

    if(CheckReadAccessStatus $path)
    {
        if(CheckWriteAccessStatus $path)
        {
            $AccessStatus = "R/W";

        } else
        {
            $AccessStatus = "R";
        }
    } else
    {
        $AccessStatus = "-RW";
    }

    $toPrint = "$env:UserName,$env:ComputerName,$currentDate,$currentTime,$path,$AccessStatus"
    Write-Host $toPrint
    add-content -path "$PSScriptRoot\$env:UserName.txt" -value "$toPrint"
}

function CheckReadAccessStatus {

    Param ([string]$path)

    $readAccessStatus = [bool]1 #0: No read access. 1: read access.

    try {

        $error.Clear()
        ii $path -ErrorAction "Stop"

        $shell = New-Object -ComObject Shell.Application
        Start-Sleep -Seconds 1
        $window = $shell.Windows() | Where-Object { $_.LocationURL -like "$(([uri]$path).AbsoluteUri)*" }
        $window | ForEach-Object { $_.Quit() }

    }

    catch [System.UnauthorizedAccessException]{ #$Error[0].Exception.GetType().FullName

        $readAccessStatus = [bool]0 

    }

    $ErrorActionPreference = "Continue"; #Reset the error action pref to default
    return $readAccessStatus
}

function CheckWriteAccessStatus {

    Param ([string]$path)

    $writeAccessStatus = [bool]1 #0: No write access. 1: write access.

    try {

        $error.Clear()
       $toPrint = "$env:UserName,$env:ComputerName,$currentDate,$currentTime,$path,3"
        add-content -path "$path\$env:UserName.txt" -value "$toPrint"

    }

    catch [System.UnauthorizedAccessException]{ #$Error[0].Exception.GetType().FullName

        $writeAccessStatus = [bool]0 

    }

    $ErrorActionPreference = "Continue"; #Reset the error action pref to default
    return $writeAccessStatus
}

Reason behind mouse properties opening is because windows have a main.cpl command that opens mouse properties. Can you change the name of your function from main to something else? main after $text="" is what's opening your mouse properties since you are running it from cmd line

Move the functions above your actual code. When you define your functions after you run your commands, the compiler will not know anything about the functions. Compiler has to read in the functions first and after that it will know to execute them when called by name.

TryMe

Function TryMe {
  Write-output "Hello" 
}

Above will fail because TryMe is defined after the execution.

Correct way

Function TryMe {
  Write-output "Hello" 
}

TryMe # Writes Hello successfully.

Move all the actual code you have after the function declarations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM