How to run a powershell function by calling the file . ps1?

Asked

Viewed 5,138 times

2

all right with you guys?

I request a help created a function that backs up virtual machines this function receives two parameters the server name and the VM name. I need to call function by running the file. ps1, I have already tried to run the file and pass the parameters to function in several ways, but the "powershell" command is executed and no action is performed or the function that this in the file is not executed, but when I run the function in the Powershell ISE or do the dot-source everything works wonders, see below the methods I have used to call the function:

using the operated call "&"

powershell.exe -command "& { C: script_backup Export-Vm.ps1 'SERVED' 'DAVNAME' }"

using the operated call "&" and doing the dot-source

powershell.exe -command "& { . C: script_backup Export-Vm.ps1 'SERVED' 'DAVNAME' }"

powershell.exe -Noninteractive -Executionpolicy Unrestricted -command "& {C: script_backup Export-Vm.ps1 SERVER NAMDAVM}"

powershell -command {Export-VM -servername SRV-LIDER-TEST -vmName VM01}

powershell "& C: script_backup Export-vm DAVNAME SERVER""

powershell -Command "& C: script_backup Export-vm -servername SERVER -vmName DAVNAME"

powershell.exe -command . . Export-VM.ps1

powershell.exe -file " 'C: script_backup Export-Vm.ps1' 'SERVED' 'DAVNAME'"

resultado do comando

and other ways not listed, all the above commands are executed (returns the prompt but does not execute the function that is in the file "Export-Vm.ps1", the worst is that it does not throw an error on the screen and does not generate an error information log anything, no longer know what to do.

Note: I am using the server "Microsoft Hyper-v Server R2"

I have already enabled the execution of scripts on my server see Comando Get-ExecutionPolicy -List

Below is the script that is in the file . ps1 that I am trying to run

function Exportar-Vm
{
    [CmdletBinding()]

    param(
         [string]$serverName,
         [string]$vmName
    )

    process{
        # Vars
        $backupPath = "D:\BACKUPs"
        $fileset = "include"
        $typeParameter = "VirtualMachine"
        $pathScriptBackup = "C:\scripts_backup"
        $FileMessage = "exportarvm.dll"
        $logName = "Evento de backup - Bacula-FD"
        $logSource = "Bacula-BackupVm"

        $getVm = Get-Vm -ComputerName $serverName -Name $vmName
        if(($getVm.GetType().Name  -eq $typeParameter) -and ($getVm.Name -eq $vmName)){
                # verify if exist file in directory BACKUPs and remove. The objective this command line is remove file "include". Just file in the directory
                Get-ChildItem -Path $backupPath"*" -File | Remove-Item
                $Date = Get-Date -UFormat "%d-%b-%Y-%H-%M-%S"
                #create directory
                $dir = New-Item -Name "$vmName-$date" -ItemType "directory" -Path $backupPath -Force
                # out file path in file include
                $dir.FullName | Out-File "$backupPath\$fileset"
                # Export vm
                Export-VM -Name $vmName -Path $dir -AsJob
                Write-EventLog -LogName $logName -Source $logSource -EntryType Information -EventId 1 -Message " $vmName exportada com sucesso! Para $dir"
        }else{
            Write-EventLog -LogName $logName -Source $logSource -EntryType Error -EventId 3 -Message " Erro maquina virtual não exportada - Backup não realizado"
        }
        Write-EventLog -LogName $logName -Source $logSource -EntryType Information -EventId 2 -Message "Fim da execução script de backup."
    }
}

1 answer

2


The central problem in these attempts is that the script Exporta-VM.ps1 just loads the function Exportar-VM, but does not invoke it.

I suggest 3 different solutions.

Solution 1

Keep the original script unchanged and call from outside the Powershell as follows

powershell.exe -command "& { . ./Exporta-Vm.ps1; Exportar-VM 'MeuServidor' 'MinhaVM' }"

Solution 2

Create an intermediate script with the following code:

. ./Exporta-VM.ps1
Exportar-VM $Args[0] $Args[1]

And make your call from outside the Powershell as follows:

powershell.exe -file Intermediario.ps1 "Meu Servidor" "Minha VM"

Solution 3

Change the original script to receive two parameters, then load the function normally, then invoke the function by passing the two parameters as arguments of the function. The script would have the format:

param(
  [string]$a,
  [string]$b
)

function Exportar-Vm
{
    [CmdletBinding()]

    param(
         [string]$serverName,
         [string]$vmName
    )

    process{
        ####################################
        # Insira sua função original aqui! #
        ####################################
    }
}

Exportar-Vm $a $b

The script would be called out of Powershell as follows:

powershell -file Exporta-VM.ps1 "Meu Servidor" "Minha VM"
  • 1

    Solution 2 solved the problem. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.