Powershell PS Credentials - windows

I'm getting confused while trying to automatically login to a share on my server through Powershell using PSCredentials.
Here is the code I'm currently using WITHOUT using PSCredentials...
#Login to server to copy installer files to desktop
Remove-PSDrive P
New-PSDrive -Name P -PSProvider FileSystem -Root \\192.168.1.85\Users2\Ross\Documents\Powershell -Credential Ross
#Copies installer files from server to the local desktop
Copy-Item -Path \\192.168.1.85\Users2\Ross\Documents\Powershell\ccsetup502.exe -Destination C:\Users\Ross\Desktop
#Executes copied installers
Start-Process C:\Users\Ross\Desktop\ccsetup502.exe -ArgumentList "/S" -Wait -Verb RunAs
#Deletes leftover installer files
Remove-Item C:\Users\Ross\Desktop\ccsetup502.exe
And here is the website I'm using to help, but whichever way I try and apply it to my own script, it never works?
http://geekswithblogs.net/Lance/archive/2007/02/16/106518.aspx
Thanks in advance!
Ross

Try this. It will prompt you for creds, but you could always create them and store them in a variable if you wish as well.
#Login to server to copy installer files to desktop
Remove-PSDrive P
New-PSDrive -Name P -PSProvider FileSystem -Root \\192.168.1.85\Users2\Ross\Documents\Powershell -Credential (Get-Credential)
#Copies installer files from server to the local desktop
Copy-Item -Path \\192.168.1.85\Users2\Ross\Documents\Powershell\ccsetup502.exe -Destination C:\Users\Ross\Desktop
#Executes copied installers
Start-Process C:\Users\Ross\Desktop\ccsetup502.exe -ArgumentList "/S" -Wait -Verb RunAs
#Deletes leftover installer files
Remove-Item C:\Users\Ross\Desktop\ccsetup502.exe

After some perseverance I managed to solve this...
Probably worth noting that I left the PSDrive removal in there for testing purposes, as you'll get an error if the script doesn't complete and you try to run it again after making changes.
#Ensure previous PSDrive 'p' is removed
Remove-PSDrive P
#Creates new PSDrive
New-PSDrive -Name P -PSProvider FileSystem -Root \\YOURSERVERNAMEHERE\YOURFILEPATHHERE
#Login to server
new-object -typename System.Management.Automation.PSCredential -argumentlist "YOURDOMAINORSERVERUSERNAMEHERE",$password
#Copies installer files from server to the local desktop
Copy-Item -Path \\YOURSERVERNAMEHERE\YOURFILEPATHHERE\ccsetup502.exe -Destination C:\YOURFILEPATHHERE
#Executes copied installers, runs the installer silently, waits until the installer has completed
Start-Process C:\YOURFILEPATHHERE\ccsetup502.exe -ArgumentList "/S" -Wait -Verb RunAs
#Deletes leftover installer files
Remove-Item C:\YOURFILEPATHHERE\ccsetup502.exe
Hopefully this helps someone else who is stuck in the future!
Thank you anyone else who contributed their efforts.

Related

How to use Remove-Item -Confirm:$false -Force properly in Windows PowerShell

So, I am writing this script in PowerShell and I am required to delete a few files in APPDATA on Windows. I wrote this line of code and it doesn't remove the item silently. It asks for confirmation even after using $Confirm:false. How do I fix this issue?
My code:
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\blob_storage" | Remove-Item -Confirm:$false -Force
I get this unwanted confirmation box every time I run the script:
Here is your modified code. I hope it will work for you.
Get-ChildItem -Path $env:APPDATA\"Microsoft\teams\blob_storage" | Remove-Item -Recurse -Force

Copying to network share does not work with powershell Copy-Item

I try to copy with powershell in Windows 10 a install folder to a network share (samba on linux)
powershell.exe -Version 5 -Command "Copy-Item -Force -Path 'install' -Recurse -Destination
'\\\\intranet.server.com\install'" -Container
It always fails, even if files can be written in the explorere and I have access, with a lot of these messages:
Copy-Item : The target file "\\intranet.server.com\install\a\b\c" is a directory, not a file.
Deleteing any existing folder works well with Remove-Item '\\intranet.server.com\install\*' -Force -Recurse
I dont know if it has to do with credentials, how can I debug this?
The problem lies in the SMB2 Redirector Cache of Windows:
We need to disable the annoying cache temporarily by doing:
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
$c = Get-SmbClientConfiguration
$dc=$c.DirectoryCacheLifetime
$fc=$c.FileInfoCacheLifetime
$fnc=$c.FileNotFoundCacheLifetime
Set-SmbClientConfiguration -Force -DirectoryCacheLifetime 0 -FileInfoCacheLifetime 0 -FileNotFoundCacheLifetime 0
// Normal kopieren hier !!!!
Set-SmbClientConfiguration -Force -DirectoryCacheLifetime $dc -FileInfoCacheLifetime $fc -FileNotFoundCacheLifetime $fnc
This is a pain in the ass, but solves the issues.

Installing windows updates remotely, using PowerShell. (some PowerCLI)

I am having a problem with a script for remote windows updates.
My goal: update all the windows servers, without using WSUS or SCCM, from PowerShell without having to log into all of them and start the update process.
For my script I am using powercli and PSWindowsUpdate modules.
For test purposes I am using a single host in the $hostname variable.
So here is what I have.
$Cred = Get-Credential
Import-Module PSWindowsUpdate
Invoke-Command -ComputerName $HostName {Import-Module PSWindowsUpdate} -Verbose -Credential $Cred
Invoke-Command -ComputerName $HostName {Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false} -Verbose -Credential $Cred
Invoke-Command -ComputerName $HostName -ScriptBlock {Get-WUInstall -MicrosoftUpdate -IgnoreUserInput -AcceptAll -AutoReboot -Confirm:$FALSE -Verbose | Out-File C:\Setup\PSWindowsUpdate.log } -credential $cred
Get-Content \\$HostName\c$\Setup\PSWindowsUpdate.log
After running the script everything works from the shut down, snapshot, power on but I can't install any updates.
I am getting the error below :
WARNING: To perform some operations you must run an elevated Windows PowerShell console.
WARNING: Can't access to machine "hostName". Try use: winrm qc
As I was searching I see that I can not make any elevation in PowerShell itself and I am reading some posts about running a CMD bat to start PowerShell in elevated rights.
It is not a problem for me to copy to every windows server the update script and have a batch to run it in elevated rights but is this the only way?
I will do the batch solution to see what I can achieve but is there any other solution in the problem I am facing?
Has anyone tried that out?
Thank you very much for your time!
I am also open for any comment on my code or fixes!
If Admin right, elevated prompts are your issue, the following may help you.
PS Code to check if running as an Administrator. If not, It will relaunch as an Administrator.
If (-Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$Arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"
Start-Process Powershell -Verb RunAs -ArgumentList $Arguments
Break
}
You will also likely need to modify ConsentPromptBehaviorAdmin at HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\ in the Registry
-
Here is a simple BAT file that will will get around the PS Execution policy and then launch the PS Script (Assuming they are named the same).
REG ADD "HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" /T REG_SZ /V ExecutionPolicy /D Unrestricted /F
Start PowerShell.exe -Command "& '%~dpn0.ps1'"
Add the end of your PS Script you can use Set-ExecutionPolicy -ExecutionPolicy Restricted -Scope LocalMachine -Force to set the execution policy back to restricted or what you have ti set to.
I ran into this issue when trying to import modules on remote machines using Invoke-Command. There's a security function that doesn't allow you to do it. You might try running the following to see if you're more successful at importing a new module.
$myPsSession = New-PSSession -ComputerName $HostName
Import-Module -Name PSWindowsUpdate -PSSession $myPsSession
I went with the task scheduler solution as it seems easier.
I created a script named WUpdates.ps1
$Timestamp=((Get-Date).ToString('dd_MM_yyyy_HH_mm'))
Import-Module PSWindowsUpdate -Verbose
Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false -Verbose
Get-WUInstall -MicrosoftUpdate -IgnoreUserInput -AcceptAll -AutoReboot -Confirm:$FALSE -Verbose | Format-Table -AutoSize | Out-File C:\Setup\WUpdates\PSWindowsUpdate_$Timestamp.log
and a script to create a schedule task named WinUpdateScheduler.ps1
Unregister-ScheduledTask -TaskName "WindowsUpdates" -Confirm:$False
$Action = New-ScheduledTaskAction -Execute C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Argument '-f "C:\Setup\WUpdates\WUpdates.ps1"'
$Trigger = New-ScheduledTaskTrigger -Once -At (get-date).AddSeconds(30)
Register-ScheduledTask -Action $Action -Trigger $Trigger -RunLevel Highest -User system -TaskName "WindowsUpdates" -Description "Running Windows updates."
then in the main script I call the schedule script and have my updates installed.
Invoke-Command -ComputerName $HostName { c:\setup\WUpdates\WinUpdateScheduler.ps1 } -Credential $Cred
If anyone want the full script I can provide it.
As of the Nixphoe and Backin answers, I will check them and I will come back later to comment on them.
Thank you very much for your time.
Invoke-WUInstall -ComputerName Test-1 -Script { ipmo PSWindowsUpdate; Get-WUInstall -AcceptAll | Out-File C:\PSWindowsUpdate.log }
-Confirm:$false –Verbose
https://4sysops.com/archives/install-windows-updates-remotely-with-the-powershell/

Remote Installation of Python using Powershell fails using Invoke-Command

I am trying to use this script to install Python on the remote computer. If I run this file directly on the server. This is the Python_Pip_Proxy_PyWinAuto.ps1 file. It works.
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
Write-Host("Hi")
$installer="C:\temp\python-3.6.2.exe"
& $installer /quiet PrependPath=1 InstallAllUsers=1 TargetDir="C:\Python36"
However if I run the Invoke-Command using the following script to run this remotely on the same server, It print's the Hi message so I know that the file is running but Python doesn't get installed.
# Getting the list of servers from a .txt file to an array #
$SRVListFile = "C:\Scripts\ServerList.txt"
$SRVList = Get-Content $SRVListFile -ErrorAction SilentlyContinue
# Copying the .exe file from a shared location to each server in the array #
# Invoking the .ps1 file which runs natively on each server #
Foreach($computer in $SRVList) {
Get-Service remoteregistry -ComputerName $computer | start-service
Copy-item -Path "E:\Software\python-3.6.2.exe" -Destination \\$computer\c$\temp -Recurse
Copy-item -Path "C:\My Files\Work\Episode 003 - MongoDB Back Up\Python_GUI.py" -Destination \\$computer\c$\temp -Recurse
Invoke-Command -ComputerName $computer -FilePath "C:\My Files\Work\Episode 003 - MongoDB Back Up\Python_Pip_Proxy_PyWinAuto.ps1"
}
What is going wrong. What should I change the code to?
Try using the -scriptblock {Your command here} parameter to execute the command inside the scriptblock parenthesis on the remote computer.
Perhaps you can do it like
$Scriptblock = {
PowerShell -file "C:\My Files\Work\Episode 003 - MongoDB Back Up\Python_Pip_Proxy_PyWinAuto.ps1"
"This is Working" | out-file "C:\Hi.txt"
}
Invoke-Command -ComputerName $computer -Scriptblock $Scriptblock
You might want to remove the Write-Host "Hi" part because that gives the script an interactive nature. If you want to check for execution on remote computer, you can use out-file cmdlet to create a file on the remote computer as an indication.

Powershell's Start-Process command doesn't start exe anywere outside Powershell ise

I'm writing simple script to unarchive (rar) a project from Teamcenter to temp directory, then run specific program (Mentor), then archive again.
I've read a lot of examples about starting exe from PS, but they mostly relate to small exes like notepad, without dlls and other resources.
In Powershell Ise the script works perfectly. But when I call the script from teamcenter, Mentor is missing dlls.
Before I run Mentor, in the script, I do:
Get-ChildItem Env:
to check environment variables and all variables exist. I tried to set environments manually, like this:
$wf_classpath = Get-ChildItem Env:WF_CLASSPATH
[System.Environment]::SetEnvironmentVariable("WF_CLASSPATH", $wf_classpath.Value, "Process")
Does not work.
I tried to set homefolder:
$mentor = Start-Process $file.FullName -Wait -WorkingDirectory $workdir
Does not work.
Then I tried to call a batch file from the script with environments, does not work.
Try call cmd.exe /c ... does not work.
Full script here, works perfect only in Powershell Ise, if I call the script from other programs, exe does not start.
$shell = new-object -com shell.application
$invocation = $MyInvocation.MyCommand.Definition
$rootpath = $PSScriptRoot
$outpath = "$($PSScriptRoot)\out"
$pathtorar = "c:\Siemens\menutils\Rar.exe"
Remove-Item -Recurse -Force $outpath
New-Item $outpath -ItemType directory
$archive = get-childitem $rootpath | where { $_.extension -eq ".rar" } | Select-Object -First 1
$arglist = "x $($archive.FullName) $($outpath)"
Start-Process -FilePath $pathtorar -ArgumentList $arglist -Wait
Remove-Item -Recurse -Force $archive.FullName
$file = get-childitem $outpath -Recurse | where { $_.extension -eq ".prj" } | Select-Object -First 1
Write-Host "$(get-date -Format yyyy-MM-dd-hh-ss)
Start process: $($file.FullName)"
$mentor = Start-Process $file.FullName -Wait
$arglist = "a -m0 -r -ep1 $($archive.FullName) $($outpath)"
Start-Process -FilePath $pathtorar -ArgumentList $arglist -Wait
Remove-Item -Recurse -Force $outpath
Read-Host -Prompt "Press Enter to exit"
What's the difference between running the script from Powershell Ise and other programs?
How should I set environment variables to run the script from other scripts/programs?
Its probably that your Current directory is not correct and WorkingDirectory in my experience is buggy. The dll's will be obtained from the current directory if they are not at the regular system paths.
Use this function before Start-Process
[IO.Directory]::SetCurrentDirectory($Dir)

Resources