powershell remote script execution errors - powershell

I notice an error " Connecting to remote server usa-chicago failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic
CategoryInfo : OpenError: (usa-chicago:String) [], PSRemotingTransportException
FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
". Below is the snippet used. Any suggestions?
All the machines are inside a workgroup.
$computers = gc "C:\servers.txt"
$source = "\\usa-chicago\c$\temp\one.jar"
$destination = "c$\july1\folder1\"
foreach ($computer in $computers) {
Invoke-Command -Computername $computer -ScriptBlock { & Copy-Item $using:source -Destination \\$using:computer\$using:destination -Force }
}

Does your user account have access both to the computer and also the share you try to copy something to? It could be that you hit the dreaded 'second hop' problem with PowerShell Remoting: https://learn.microsoft.com/en-us/powershell/scripting/learn/remoting/ps-remoting-second-hop?view=powershell-7
If this is the problem, there are some workarounds for that. What i like to do is:
In the Invoke Command, create a Scheduled Task with the commands you'd like to execute and pass the credentials into it, execute it, and delete it after.

Related

Powershell forum with button calling script

I have a powershell forum for level 1.
Now it has been asked to add a button that calls an script for solving automatic outlook issues.
The script works when i call it direct on the computer itself (via .\outlook.ps1)
When i add it to the button it does not work.
The button itself works and is visible.
example code:
$button_Outlookrest_Click={
Get-ComputerTXTBOX
Add-logs -text "$ComputerName - Create new Outlook profile"
function button{
Copy-Item -Path "D:\path\Repair_outlook_Profile.ps1" -Destination "\\$ComputerName\C$\local" -Recurse
Invoke-Command -ComputerName $ComputerName -ScriptBlock {C:\local\Repair_outlook_Profile.ps1}
}
}
I have tested the code individual, and the following is working:
Copy-Item -Path "D:\path\Repair_outlook_Profile.ps1" -Destination "\\replaced-with-targetcomputer\C$\local" -Recurse
When i whant to call the script, i use the following:
Invoke-Command -ComputerName $ComputerName -ScriptBlock {C:\local\Repair_outlook_Profile.ps1}
However, above text provides me below error:
PS C:\Users\admin> Invoke-Command -ComputerName targetcomputer -ScriptBlock {C:\local\Repair_outlook_Profile.ps1}
[targetcomputer] Connecting to remote server targetcomputer failed with the following error message : WinRM cannot
complete the operation. Verify that the specified computer name is valid, that the computer is accessible over the
network, and that a firewall exception for the WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public profiles limits access to remote computers within the same local
subnet. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (clienttarget:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionStateBroken
i want to avoid them using powershell, as its not the idea of this button.
in the script itself, it does not copy the file to the target computer, it does not run the script using the invoke command.
Is this blocked by company firewall?
Do i have something wrong in my code?
An example button that works without any problem is:
$button_DriverQuery_Click={
$button_DriverQuery.Enabled = $False
Get-ComputerTxtBox
$DriverQuery_command="cmd.exe"
$DriverQuery_arguments = "/k driverquery /s $ComputerName"
Start-Process $DriverQuery_command $DriverQuery_arguments
$button_DriverQuery.Enabled = $true
}
Only this aditional button does not work. And i cannot figure it out at the moment.
What am i doing wrong here?
thank you.

Trying to Retrieve A Reg Value From Remote Machines Using Powershell

I am trying to retrieve a registry value from each computer using a for each loop and then output that value to a folder in a csv.
That part works fine. The part I am having an issue with is having powershell connect to the remote computers.
This is running internal only
I have admin rights across all workstations
Firewalls are configured to allow all traffic to pass
When I run this script I get this error for every workstation it tried to connect to:
Enter-PSSession : Connecting to remote server workstationX failed with
the following error message : WinRM cannot complete the operation.
Verify that the specified computer name is valid, that the computer
is accessible over the network, and that a firewall exception for the
WinRM service is enabled and allows access from this computer. By
default, the WinRM firewall exception for public profiles limits
access to remote computers within the same local subnet. For more
information, see the about_Remote_Troubleshooting Help topic. At
C:\Users\Rich_Ellis\Desktop\O365\O365Channels\O365Channel.ps1:5 char:2
+ {Enter-PSSession -ComputerName $Computer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (workstationX:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
My script is:
$Computers = Get-Content "C:\Users\Rich_Ellis\Desktop\O365\O365Channels\computers.txt"
foreach ($Computer in $Computers)
{Enter-PSSession -ComputerName $Computer
$key = 'HKLM:\SOFTWARE\Microsoft\Office\CLickToRun\Configuration'
(Get-ItemProperty -Path $key -Name CDNBaseUrl).CDNBaseUrl | Export-CSV -path "\\s00itstorage\OfficeChannel\$($env:COMPUTERNAME)-O365Channel03292018.csv"}
Any help would be appreciated. TIA
Molding a previous answer to your use-case:
$HKEY_LOCAL_MACHINE = 2147483650
$GwmiArgs = #{
Class = 'StdRegProv'
Namespace = 'Root\Default'
List = $True
}
ForEach ($Computer in #(Get-Content -Path 'C:\Users\Rich_Ellis\Desktop\O365\O365Channels\computers.txt'))
{
$GwmiArgs['ComputerName'] = $Computer
$Registry = Get-WmiObject #GwmiArgs
$Registry.GetStringValue(
$HKEY_LOCAL_MACHINE,
'SOFTWARE\Microsoft\Office\ClickToRun\Configuration',
'CDNBaseUrl'
).sValue | Export-CSV -Path "\\s00itstorage\OfficeChannel\$Computer-O365Channel03292018.csv"
}
This uses wmi instead of psremoting to poll the information which may be easier to rely on as it is already configured/enabled on most PCs and can utilize IP addresses due to DCOM/RPC (psremoting only supports kerberos by default)
This solution can be further improved by using Invoke-WmiMethod instead of creating a wmi object for each poll, but I haven't done the work already for that!

Invoke-Command with parameter computername on local device

I'm writing a script that needs to be used on multiple devices.
This script uses an Invoke-command to connect to a specified server.
This script also has to be run on this same server.
Invoke-Command -ComputerName $Server -Credential $Cred -ScriptBlock {Write-Host "test"}
It's no problem to run this script from remote devices but when running it on the server used in $Server I get the following error
Connecting to remote server DC01 failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (DC01:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
My question is if there is a possibility to fix it or if I have to write an if/else to check on which server it's running atm.

Powershell Workflow to reboot computers

Code:
workflow Test-RemoteReboot{
param ([string[]]$serverNames)
foreach -parallel($server in $serverNames){
Restart-Computer -PSComputerName $server -Wait -Force
}
}
Test-RemoteReboot SP,SP2
Issue:
this is a small excerpt from a pretty long workflow I built in powershell. By all accounts, this should work but I get the following error (even when running this script in isolation):
Microsoft.PowerShell.Utility\Write-Error : The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: The computer SP2 is
skipped. Fail to retrieve its LastBootUpTime via the WMI service with the following error message: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA).
At line:433 char:25
+ ... Receive-Job -Job $job -Wait -Verbose -Debug -ErrorAction ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], ActionPreferenceStopException
+ FullyQualifiedErrorId : System.Management.Automation.ActionPreferenceStopException,Microsoft.PowerShell.Commands.WriteErrorCommand
+ PSComputerName : [localhost]
I looked into the RPC server unavailable issue. Firewall is down, RPC Service is running, Servers are on domain, Workflow running from domain member computer, as domain admin. I can successfully PSRemote into the machines and do whatever. I can even do this:
workflow Test-LocalRebootRemotely{
param ([string[]]$serverNames)
foreach -parallel($server in $serverNames){
InlineScript { Restart-Computer -Force } -PSComputerName $server
}
}
Test-LocalRebootRemotely SP,SP2
The problem is, is that I need a return value to determine if I need to reboot and handle other logic outside of the remote computer. I do notice that there is an abnormal pause just before it errors. So maybe it is a timeout? anyone have a similar issue?
You can try the Restart-Computer cmdlet with the -Protocol WSMan parameter instead of the default DCOM over RPC protocol (-Protocol DCOM).
This would confirm that your RPC network packets are blocked somewhere.

"Access denied" error when trying to enumerate drives on remote computers

I am trying to run a PowerShell command to get the total disk space of all drives for all our remote servers. When I run the command I am getting the error below. I have a text file which has names of the servers and I have also confirmed that WinRM is configured and is running.
$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
Invoke-Command -ComputerName $s {Get-PSDrive}
}
Error:
[ahv-a2acortst02] Connecting to remote server failed with the following error
message : Access is denied.
For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
Agreed that the message 'Access is denied' is a dead giveaway that you don't have access.
I would create a credential variable and make sure it is a credential that has rights to the remote system.
$Creds = Get-Credential
then change your code to the following (I added the -scriptblock and the bolded text
$Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt"
foreach ($s in $Servers) {
Invoke-Command -ComputerName $s -ScriptBlock {Get-PSDrive} -Credential $creds
}