Remove a file using powershell through admin account - powershell

Brief summary of what I'm trying to do.
I have a script in powershell that takes 2 files and reads in the embedded credentials and stores them in a variable to which then I can run administrative commands from.
This works great, however, after the files are read and the key is stored, I'm trying to delete the 2 files and I keep getting the following error:
Start-Process : Parameter set cannot be resolved using the specified
named parameters. At \mars\Client-Installs\NetSmart
Test3\Setup.ps1:137 char:15
+ Start-Process <<<< -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path
$file1 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
Start-Process : Parameter set cannot be resolved using the specified
named parameters. At \mars\Client-Installs\NetSmart
Test3\Setup.ps1:138 char:15
+ Start-Process <<<< -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path
$file2 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.StartProcessCommand
The account I'm running with is part of domain admin and when I look in task manager I can see it running in Administrative mode.
I also know that the folder path where the files reside also have full share and security access to.
Here is a snippit of my code (The bottom 2 lines are the ones that don't seem to work)
function Authentication
{
#---------------------------------------------------
#Authenticate Admin Account using encrypted password
#---------------------------------------------------
$TempFolder = $env:temp
#The 2 lines underneath is if you are running the auth files from the same directory
#$global:AESKeyFilePath = $path + "\aeskey.txt"
#$global:SecurePwdFilePath = $path + "\credpassword.txt"
#Move the files to the temp folder
$global:file1 = $path + "\aeskey.txt"
$global:file2 = $path + "\credpassword.txt"
Copy-Item -Path $file1 -Destination $TempFolder -force
Copy-Item -Path $file2 -Destination $TempFolder -force
#If you choose to run it from the temp directory comment the lines above and uncomment the 2 below.
$global:AESKeyFilePath = $TempFolder + "\aeskey.txt"
$global:SecurePwdFilePath = $TempFolder + "\credpassword.txt"
$global:userUPN = "domain\user"
#use key and password to create local secure passwordtemp
$global:AESKey = Get-Content -Path $AESKeyFilePath
$global:pwdTxt = Get-Content -Path $SecurePwdFilePath
$global:securePass = $pwdTxt | ConvertTo-SecureString -Key $AESKey
#create a new psCredential object with required username and password
$global:adminCreds = New-Object System.Management.Automation.PSCredential($userUPN, $securePass)
#Remove the files below
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file1 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file2 -Force" -WorkingDirectory $path -NoNewWindow -PassThru
}

You cannot specify -NoNewWindow and -WindowStyle together, its contradicting.
See Get-Command Start-Process -Syntax for the parameter sets.
I hope below way is what you need. Just use -WindowStyle Hidden.
Start-Process -FilePath "powershell.exe" -Credential $adminCreds -WindowStyle Hidden -ArgumentList "Remove-Item -Path $file2 -Force" -WorkingDirectory $path -PassThru

Related

How to use credentials in powershell script to copy file to a destination server?

I am trying to copy file from my local machine to a server destination
My Script: Copy-Item –Path D:\Test.txt –Destination '\\10.10.X.X\c$'
Error:
Copy-Item : The network path was not found
At D:\PS_Test_script.ps1:1 char:2
+ Copy-Item –Path D:\Test.txt –Destination '\\10.10.X.28X\c$'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
The server has credentials, I am guessing that, I have to invoke something to use the credentials.
To keep it somewhat simple, to copy to a folder share which requires different credentials to access you can use New-PSDrive to map a drive using those credentials
$desiredMappedDrive = 'J'
$desiredMappedDrivePath = '\\10.10.X.X\c$' # Map to administrative C: drive share requires administrator credentials)
$source = 'D:\Test.txt'
$destination = "${desiredMappedDrive}:\temp"
# Get-Credential cmdlet will request that you enter a username and password that has access to the share
New-PSDrive -Name $desiredMappedDrive -PSProvider FileSystem -Root $desiredMappedDrivePath -Credential (Get-Credential)
# after drive is mapped copy file over
Copy-Item -Path $source -Destination $destination -Verbose
Here is a whole different approach using PSSession no need to map any drives:
$targetComputerName = "127.0.0.1"
$Session = New-PSSession $targetComputerName -Credential 'username'
$DestinationPath = "C:\temp"
$source = 'D:\Test.txt'
Copy-Item -Path $source -ToSession $Session -Destination $DestinationPath
$Session | Remove-PSSession
If you want to execute it as a script you would have to create a [SecureString] and build a credential object.

send file to remote folder powershell

this is what i would use for copying without asking for password, because i want to schedule this script
$Source = "d:\test\myZipFile.zip"
$Dest = "\\REMOTE_ip\D$\test"
$Username = "Administrator"
$Password = ConvertTo-SecureString "PasswordOFRemotePC" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($Username, $Password)
New-PSDrive -Name J -PSProvider FileSystem -Root $Dest -Credential $mycreds -Persist
Copy-Item -Path $Source -Destination "d:\test\myZipFile1.zip"
But it gives me error
New-PSDrive : The network resource type is not correct At D:\test\copy.ps1:7 char:1
New-PSDrive -Name J -PSProvider FileSystem -Root $Dest -Credential $m ...
+ CategoryInfo : InvalidOperation: (J:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
Going by the title of your question, I think you are overdoing this.
In your scheduled task, decide which user account should be running the script. That user should have Read access to the machine's local D:\Test folder and must have Write/Modify permissions to the remote path \\REMOTE_ip\D$\test.
You can set the task so that particular user does not even have to be logged in.
The executable to run is PowerShell.exe and the arguments are -File <PathToTheScript.ps1>
(for that, the task-running user must have Read & Execute permissions on the location of the script file)
The script itself can then be as simple as:
$Source = "d:\test\myZipFile.zip"
$Dest = "\\REMOTE_ip\D$\test"
Copy-Item -Path $Source -Destination $Dest -Force

Any ideas on why i am receiving this error? Any help appreciated. Thnx

Uninstalling :
The term 'C:\temp\install\Deploy-Application.exe' is not recognized 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.
+ CategoryInfo : ObjectNotFound: (C:\temp\install\Deploy-Application.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : WKPF26YSKX
This is the code ran:
function Install-File {
Invoke-Command `
-Session $global:session `
-ScriptBlock{
if( -not (Test-Path -Path "V:\") ) {
New-PSDrive -Name "V" -PSProvider "FileSystem" -Root "\\lounaswps01\idrive\D907ATS" -Credential (Get-Credential -Credential "slb8031a") -Scope global
}
$Global:certRequestID = $global:objTemp.CRID
# Assign server path and local path variables w/ given CR ID
$serverPath = "v:\" + $Global:certRequestID
$localPath = "C:\temp\" + $Global:certRequestID
dir $serverPath
dir $localPath
#Copy-Item -Path $serverPath -Destination $localPath -Recurse -Force | Out-Host
# Check for atsinst.bat first - run it if it exists. Else offer uninstall/install options
if(Test-Path -LiteralPath "${localPath}\install\atsinst.bat") {
Invoke-Expression -Command " ${localPath}\install\atsinst.bat -DeployMode 'Silent' | Out-Host "
}
Write-Host "`nUninstalling ${certRequestID}: "
Invoke-Expression -Command " ${localPath}install\Deploy-Application.exe -DeployMode 'Silent' -DeploymentType 'Uninstall' | Out-Host"
#Start-process -FilePath "${localPath}\install\Deploy-Application.exe" -argumentList "-DeployMode Silent -DeploymentType Uninstall" -wait -noNewWindow
Write-Host "`nInstalling ${certRequestID}: "
Invoke-Expression -Command " ${localPath}\install\Deploy-Application.exe -DeployMode 'Silent' | Out-Host "
}
# Offer to delete files from host
$prompt = Read-Host -Prompt "`nDelete ${certRequestID} from the user's temp folder? (y/n)"
if($prompt.ToLower() -eq "y") {
Write-Host "`nDeleting files..."
Remove-Item -LiteralPath $localPath -Recurse -Force
}
}
You're missing a backslash in one of the lines for uninstalling?
Invoke-Expression -Command " ${localPath}install\Deploy-Application.exe
Should Read:
Invoke-Expression -Command " ${localPath}\install\Deploy-Application.exe

PowerShell 5.1 Set-Acl

I try to use Set-Acl in my PowerShell script if just I make
$my_acl = Get-Acl "C:\"
Set-Acl D:\ $my_acl
This work in Admin
but if I try to launch script in User en elevate to Admin
$my_acl = Get-Acl "C:\"
$arg5={param($my_acl,)(Set-Acl D:\ $my_acl )}
Start-Process powershell.exe -ArgumentList "-noexit -command & {$arg5} $my_acl" -Verb RunAs
I got this error
Set-Acl : AclObject
Au caractère Ligne:1 : 19
+ & {param($my_acl)(Set-Acl D:\ $my_acl )} System.Security.AccessContro ...
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument : (System.Security...rectorySecurity:String) [Set-Acl], ArgumentExceptio
n
+ FullyQualifiedErrorId : SetAcl_AclObject,Microsoft.PowerShell.Commands.SetAclCommand
EDIT:
Thank for the solution PRASOON KARUNAN V the solution is really nice, but I just make:
Start-Process powershell -ArgumentList "Get-Acl C:\ | Set-Acl D:\" -Credential ($credentials_admin)
Start-Sleep -Seconds 3
Start-Process powershell -ArgumentList "Get-Acl C:\Users\$($my_user) | Set-Acl D:\$($my_user)" -Credential ($credentials_admin)
I just pipe out the result of Get-Acl in my Set-Acl and it's ok.
Your script have problems.
You don't need to set the scrtipblock to a variable, better to call
it directly.
There was a unwanted comma in param block.
Parenthesis are not required here (Set-Acl D:\ $my_acl )
$my_acl = Get-Acl "C:\"
Start-Process powershell.exe -ArgumentList "-noexit -command & {param(`$my_acl) Set-Acl D:\ `$my_acl} $my_acl" -Verb RunAs
Like below, we have to escape the $ sign so that the value no not invoked when those are using in double quotes.
`$My_acl

Install Chrome on Windows with a .bat file using PowerShell

I was searching around and found a few hints but a few detail pieces are missing.
Here is what I have:
install-chrome.bat
PowerShell -NoProfile -Command "&{Start-Process PowerShell -ArgumentList '-NoProfile -File install-chrome.ps1' -Verb RunAs}"
install-chrome.ps1
$client = New-Object System.Net.WebClient;
$client.DownloadFile("https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe", ".\ChromeStandaloneSetup64.exe");
.\ChromeStandaloneSetup64.exe /silent /install ;
Two things are not working as expected:
I still get a UAC popup even though the posts I found state that the above should start PowerShell in Admin mode.
I was expecting .\ would download the .exe to the directory the .ps1 and .bat scripts are located.
Any hints on how to solve this?
EDIT:
Thanks to the reply from #TheIncorrigible1 I managed to solve the second part. Both options work more or less (it downloads it, but the installation throws an error locally) when I execute them directly in PowerShell:
< V3
$PSScriptRoot = Split-Path -Parent -Path $script:MyInvocation.MyCommand.Path
$uri = "https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe"
$path = "$PSScriptRoot\ChromeStandaloneSetup64.exe"
$client = New-Object System.Net.WebClient
$client.DownloadFile($uri, $path)
& $path /install
V3+
$uri = "https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe"
$path = "$PSScriptRoot\ChromeStandaloneSetup64.exe"
Invoke-WebRequest -Uri $uri -OutFile $path
& $path /install
But the batch still throws errors:
At line:1 char:62
+ ... tart-Process PowerShell -Verb RunAs -ArgumentList -NoProfile, -File, ...
+ ~
Missing argument in parameter list.
At line:1 char:69
+ ... ocess PowerShell -Verb RunAs -ArgumentList -NoProfile, -File, 'C:\Pro ...
+ ~
Missing argument in parameter list.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingArgument
Two things-
You don't need to wrap your batch command to powershell in a scriptblock and -ArgumentList expects an array of string arguments:
powershell.exe -NoProfile -Command "Start-Process -FilePath powershell.exe -ArgumentList #('-NoProfile', '-File', '%~dp0install-chrome.ps1') -Verb RunAs"
There's an automatic variable, $PSScriptRoot, to determine where your root directory is:
$uri = 'https://dl.google.com/chrome/install/ChromeStandaloneSetup64.exe'
if (-not $PSScriptRoot) {
$PSScriptRoot = Split-Path -Parent -Path $script:MyInvocation.MyCommand.Definition
}
$outFile = "$PSScriptRoot\ChromeStandaloneSetup64.exe"
if ($PSVersionTable.PSVersion.Major -lt 3) {
(New-Object -TypeName System.Net.WebClient).DownloadFile($uri, $outFile)
}
else {
Invoke-WebRequest -Uri $uri -OutFile $outFile
}
& $outFile /silent /install
Here you go:
$Path = $env:TEMP; $Installer = "chrome_installer.exe"; Invoke-WebRequest "http://dl.google.com/chrome/install/375.126/chrome_installer.exe" -OutFile $Path\$Installer; Start-Process -FilePath $Path\$Installer -Args "/silent /install" -Verb RunAs -Wait; Remove-Item $Path\$Installer