execute script with administrator permission

2

I have the following code snippet:

foreach($File in $(Get-ChildItem -Path $FromPath)){ 
        $ObjFolder.CopyHere($File.fullname, $CopyOptions);
    }

It copies the files to the windows folder, however the users are not allowed to do this, I'm trying to use the following excerpt:

Invoke-Command -ScriptBlock $script -Credential contoso\admin;

But it is not working, would you have to save the credentials in a variable, so that it does not ask permission for every file that will be copied?

Full script:

function getCredencial(){
    $usario = Read-Host "Usuario"
    $senha = Read-Host -AsSecureString "Senha"

    return New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $usario, $senha
}

$script = { 

    $FONTS = 0x14;

    $FromPath = "\servidor01\arquivos\fontes\";

    $ObjShell = New-Object -ComObject Shell.Application;
    $ObjFolder = $ObjShell.Namespace($FONTS);

    $CopyOptions = 4 + 16;
    $CopyFlag = [String]::Format("{0:x}", $CopyOptions);

    foreach($File in $(Get-ChildItem -Path $FromPath)){ 
        $ObjFolder.CopyHere($File.fullname, $CopyOptions);
    }
}
$credenciais = getCredencial;
Invoke-Command -ScriptBlock $script -Credential $credenciais;
    
asked by anonymous 18.11.2014 / 11:56

2 answers

0

Searching the net found a solution:

Using the command Get-Credential it is possible to do the same thing.

I assign credentials to a variable:

$credential = Get-Credendial contoso\admin;

and no Invoke-Command use my variable:

Invoke-Command -ComputerName $env:COMPUTERNAME -ScriptBlock $script -Credential $credential ;

Note: Using Get-Credential , a dialog box will appear to enter the user and password, and setting contoso\admin after Get-Credential , you only have to enter the password, since the user field is already filled in. p>

More Get-Credential information Here

    
18.11.2014 / 18:07
3

Create a function that prompts the user for a password and returns a credential object:

function getCredencial(){
    $usario = Read-Host "Usuario"
    $senha = Read-Host -AsSecureString "Senha"

    return New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $usario, $senha
}

#código principal....
$credencial = getCredencial
Invoke-Command -ScriptBlock $script -Credential $credencial -ComputerName $env:COMPUTERNAME

Read-Host -AsSecureString changes the characters entered by asterisks in this way does not display the contents of the password.

References:

Get FQDN Hostname

Parameter set can not be resolved using the specified named parameters

    
18.11.2014 / 12:03