Script working from powershell ISE but not from powershell - powershell

I am trying to connect to vsphere using powercli and the powershell script contents are below,
# test.ps1
Set-PowerCLIConfiguration -Scope User -InvalidCertificateAction Ignore -Confirm:$False
Connect-VIServer server_name -User username -Password pass
If I execute the script from powershell ISE it's working fine and it will connect. But the same is not happening from powershell and getting below error
Connect-VIServer : 8/11/2021 4:00:32 PM Connect-VIServer Error: Invalid server certificate. Use
Set-PowerCLIConfiguration to set the value for the InvalidCertificateAction option to Prompt if you'd like to connect
once or to add a permanent exception for this server.
Additional Information: Could not establish secure channel for SSL/TLS with authority 'x.x.x.x'.
At line:1 char:1
+ Connect-VIServer x.x.x.x -User username -Password pass
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [Connect-VIServer], ViSecurityNegotiationException
+ FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_Reconnect_CertificateError,VMware.VimAutomation.ViCore.
Cmdlets.Commands.ConnectVIServer

Try to run the powershell command shell in an elevated level.
run your script from an elevated powershell command shell.
shift + Right mouse click powershell icon and select run as Administrator
once this is opened run your script.

Related

Powershell VSCode invoke-command from localhost different user for SCCM

Because VSCode is not able to run a powershell console and debug it as a different user i am trying to get arround it with invoked credentials like this:
Start-Service -Name "WinRM"
$cred = Get-Credential -Credential domain\myuser
Invoke-command -Credential $cred -Computer "localhost" -scriptblock {
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
Set-Location 'XXX:' # my sccm site code
Import-CMComputerInformation -CollectionName "All Systems" -ComputerName "TestComputer" -MacAddress "00:00:00:00:00:69"
}
If i start it in the debugger of VSCode (F5) it starts but cant connect then to the SCCM Server infrastructure. Could someone help me to solve this issue?
Error:
Cannot find drive. A drive with the name 'XXX' does not exist.
+ CategoryInfo : ObjectNotFound: (XXX:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : localhost
This command cannot be run from the current drive. To run this command you must first connect to a Configuration Manager drive.
+ CategoryInfo : DeviceError: (Microsoft.Confi...ormationCommand:ImportComputerInformationCommand) [Import-CMComputerInformation], InvalidOperationException
+ FullyQualifiedErrorId : CommandCannotExecuteFromCurrentDrive,Microsoft.ConfigurationManagement.Cmdlets.Oob.Commands.ImportComputerInformationCommand
+ PSComputerName : localhost
If i logoff from my machine and login with my admin credentials and execute everything in the invoke-command scriptblock it works.
As i am not allowed to work like this by our company policy's is there maybe a alternative way or something i can do to use the visual studio code debugger?
Have you logged onto the SCCM site server interactively with the credentials you are using and opened the console at least once? I believe this initial first opening is required before the drive is accessible remotely...

Running cmd command to remote host on PowerShell

I need to run in PowerShell script cmd command, which command will be running on remote cmd line. So I put in my script
Invoke-Command -ComputerName $line -scriptblock {cmd.exe /c "whoami"} -credential $Cred
and it works, but only if on remote host was run Enable-PSRemoting -Force
Otherwise I get error:
[192.168.1.1] Connecting to remote server 192.168.1.1 failed with the following error message : Access denied. For more information, see the about_Remote_Trou
bleshooting Help topic.
+ CategoryInfo : OpenError: (192.168.1.1:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
I need run that command to many (about 200) remote hosts, so the question is how can I do this without manually running on each remote host Enable-PSRemoting -Force? Server is in domain but romote hostd don't.
If your servers are on a domain, you could enable PS Remoting on them all via Group Policy: https://www.briantist.com/how-to/powershell-remoting-group-policy/

Running a Setup.exe from a network share, via Invoke-Command in Powershell

PSEXEC started to give me some trouble, and I decided to recode in PowerShell.
This batch command used to work for me, before PSEXEC started messing things up:
psexec -accepteula \\<ServerToBeUpdated> -u <User> -p <Password> cmd /c "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe /silent /Update"
I'm trying to do this with Invoke-Command in Powershell, but with no luck so far.
I've tried many combinations, and googled a lot, and overall it seems that PowerShell is not fond of the UNC path I'm trying to install from.
Here is what I've got:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Start-Process -FilePath "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe" -ArgumentList "/update /silent" -wait }
I get this error message:
This command cannot be run due to the error: Access is denied.
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
+ PSComputerName : DE5441
Some people say that the setup.exe has be copied locally on the remote server. But this does not seem to be an option for me, mainly for two reasons.
My setup.exe identifies that it is not in the right path, then it kills the local the setup.exe process, and automatically starts a new setup.exe from the UNC path.
I also need the ExitCode from my setup.exe, which gets lost when the "killing" starts as mentioned in reason number 1.
As a final note, I did grant access for PowerShell to run remotely with the Enable-PSRemoting command, and I also get expected results from this simple test:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Hostname }
You are experiencing a so called double-hop authentication issue. If using normal authentication you will not be able to authenticate to a second computer from the machine you are invoking the command on.
To solve this you can use CredSSP.
To enable CredSSP on the machine that is being called:
Enable-WSManCredSSP -Role Server -force
To enable CredSSP on the client:
Enable-WSManCredSSP -Role Client -DelegateComputer server.domain.com -force
The -delegateComputer parameter expects a FQDN but also takes wildcards.
After enabling CredSSP you can use it to invoke your command with the parameter -authentication CredSSP

remove-computer cmdlet access denied

I am trying create a script to remove a computer from a domain using remove-computer -unjoincredentials domain\admin -passthru However, I consistently receive an error stating that
remove-computer : Failed to unjoin computer 'web140127105714' from domain 'domain.com' with the following error
message: Access is denied.
At line:1 char:1
+ remove-computer -UnjoinDomainCredential domain\admin -PassThru
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (web140127105714:String) [Remove-Computer], InvalidOperationException
+ FullyQualifiedErrorId : FailToUnjoinDomain,Microsoft.PowerShell.Commands.RemoveComputerCommand
The account I am using is a domain administrator with full access. I have confirmed that the account can manually unjoin from the domian.
Some operations on the console require you to be on an elevated PowerShell session. You can start your PowerShell session as Admin by right clicking on it and choosing 'Run as Administrator'. Then run the remove-computer cmdlet in that console session. Default title of the Administrator PowerShell console is 'Administrator : Windows PowerShell'. You can identify the window that way
Sounds like the OP found his answer, so here is a powershell self elevating example for future readers. Add to the top of your scripts and it will re-launch itself elevated so we don't have to right click and 'Run As Administrator'.
$WID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$WIP=new-object System.Security.Principal.WindowsPrincipal($WID);
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator;
If ($WIP.IsInRole($adminRole)){
}else {
$newProcess = new-object System.Diagnostics.ProcessStartInfo 'PowerShell';
$newProcess.Arguments = $myInvocation.MyCommand.Definition
$newProcess.Verb = 'runas'
[System.Diagnostics.Process]::Start($newProcess);Write-Host 'Prompting for Elevation'
exit
}
#####################
# Add Scripts Below #
#####################
Write-Host 'ElevatedCodeRunsHere';
Write-Host 'Press any key to continue...'
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
Powershell start-process script calls a second script - how to make one script only
There is no such parameter as -unjoincredentials
http://technet.microsoft.com/en-us/library/hh849816.aspx

Not able to run exe from powershell for a system user

I am trying to run an exe from powershell script on windows-7 64 bit machine. In this script I want to run exe as another user. It works when user invoking script is an actual user. But in my case, this powershell script will be executed from system user account and for system user script does not work. Here in a simple code I am using to open notepad. This code fails for system user.
$username = 'MyDomain\MyUser'
$password = 'mypswd'
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process -Credential $cred "notepad.exe"
I have set execution policy to unrestricted. When I run this script for system user, then I get error as
Start-Process : This command cannot be executed due to the error: Access is den
ied.
At D:\temp\trythis.ps1:4 char:14
+ Start-Process <<<< -Credential $cred "notepad.exe"
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
Is there any way in which I can run this script for system user?
The most likely problem here is a permissions one (The only way I could reproduce your issue was by setting a Deny entry for the account).
I would suggest the following to confirm the permissions are correct. Instructions are for Windows XP, SP3 - adjust for your version!
Right-click on "notepad.exe" and click Properties
Click the Security tab
Click the Advanced button
Click the Effective Permissions tab
Click the Select... button
Enter the account you want to check and confirm that the account has appropriate read and execute permissions.