To PSSession or Not to PSSession
I'm writing a function to clean up old user profiles, removing them based on a cutoff date. It also includes code for two related tasks, but I'm having trouble deciding how best to approach them.1. The function optionally (but by default) will backup any user data to C:\UserBackup2. After removing old profiles, the function will cycle through the remaining user profiles and empty out C:\Users\$user\AppData\Local\Temp, and finally empty C:\Windows Temp.
With both of these tasks, I thought it would be more efficient to have the target machine handle this work (especially the backup: why have the computer running the function handle the copying over the network when it's just getting moved to another folder locally?).But this is bringing with it a host of complications: Queueing each of the commands is important so the hard drive doesn't...
This topic first appeared in the Spiceworks Community
I'm writing a function to clean up old user profiles, removing them based on a cutoff date. It also includes code for two related tasks, but I'm having trouble deciding how best to approach them.1. The function optionally (but by default) will backup any user data to C:\UserBackup2. After removing old profiles, the function will cycle through the remaining user profiles and empty out C:\Users\$user\AppData\Local\Temp, and finally empty C:\Windows Temp.
With both of these tasks, I thought it would be more efficient to have the target machine handle this work (especially the backup: why have the computer running the function handle the copying over the network when it's just getting moved to another folder locally?).But this is bringing with it a host of complications: Queueing each of the commands is important so the hard drive doesn't...
This topic first appeared in the Spiceworks Community
Similar Messages
-
Same command works with enter-pssession but not invoke-command
I'm trying to run an executable remotely with powershell. Right now I'm trying to install Office 2013 SP1, but in the past I've had the same issue with other executables.
The command I'm running is as follows:
Invoke-Command -computername computer01 -scriptBlock {C:\windows\Temp\proplussp2013-kb2817430-fullfile-x86-en-us.exe /quiet}
It finishes almost immediately, returning no result, having not installed anything.
However, if I do the following, it works just fine:
Enter-PSSession computer01
C:\windows\Temp\proplussp2013-kb2817430-fullfile-x86-en-us.exe /quiet
Any idea what my problem with Invoke-Command is?
Eric HodgesI did an Enter-PSSession, then ran the command using start-process. It hangs indefinitely. I did have to change the command a little, because I couldn't just put the whole command in quotes - that gave me an error saying the file wasn't found. I separated
it into -filepath and -argumentlist params. Below is what I ran:
Enter-PsSession -computername computer01
start-process -filepath "C:\windows\Temp\proplussp2013-kb2817430-fullfile-x86-en-us.exe" -argumentlist "/quiet"
This resulted in the session hanging indefinitely. So here is where I'm at:
Enter-PsSession then running the command works
Invoke-command with the command immediately finishes, with no output and the program doesn't actually install
Enter-PsSession then running start-process hangs indefinitely
Invoke-Command plus start-process hangs indefinitely
I was curious to see if this held true with other programs, so I tried installing a program from HP with a silent switch and got identical behavior throughout all four scenarios listed above.
Turning off on-access A/V protection made no difference.
Finally, regarding mjolinor's question about the program running in non-interactive environments: to the best of my knowledge the program can - but I'm not positive. I would assume, however, that invoke-command would build the same sort of environment as
Enter-PsSession does, and it works there.
Eric Hodges -
Enter-PSSession does not work when a IPV6 address is entered as the -Computer value.
I cannot get Enter-PSSession to work with a specific IPV6 address and when TrustedHosts is also set to this address.
NOTE: If TrustedHosts is set to "*", then the command succeeds, so I'm pretty sure the target is configured correctly to allow remote access.
Example:
set-item wsman:\localhost\Client\TrustedHosts "fc00:10:114:247:2d0b:6bf8:c982:ce10"
ENTER-PSSession -Computer fc00:10:114:247:2d0b:6bf8:c982:ce10 -Credential <somecred>
ENTER-PSSession : Connecting to remote server [fc00:10:114:247:2d0b:6bf8:c982:ce10] failed with the following error message : The WinRM client cannot process the request. Default authentication may
be used with an IP address under the following conditions: the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure
TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more information on how to set TrustedHosts run the following command: winrm help config. For more
information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ ENTER-PSSession -Computer fc00:10:114:247:2d0b:6bf8:c982:ce10 -Credential Admini ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (fc00:10:114:247:2d0b:6bf8:c982:ce10:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailedPing works by IPv6 or name.
For name, I put the IPv6 address and name in my hosts file because during testing, I move from a domain to a workgroup occasionally.
Example:
Target
ipconfig
IPv6 Address. . . . . . . . . . . : fc00:10:114:247:44d1:f91f:2ceb:b032
Client Computer
/etc/hosts
fc00:10:114:247:44d1:f91f:2ceb:b032 slo-2k8r2-64-5
Ping slo-2k8r2-64-5
Reply from fc00:10:114:247:44d1:f91f:2ceb:b032: time<1ms
Powershell
set-item wsman:\localhost\Client\TrustedHosts "fc00:10:114:247:44d1:f91f:2ceb:b032"
ENTER-PSSession -Computer fc00:10:114:247:44d1:f91f:2ceb:b032
// ENTER-PSSession : Connecting to remote server [fc00:10:114:247:44d1:f91f:2ceb:b032] failed with the following error message : The WinRM client cannot process the request. Default authentication may
Again, if I set Trustedhosts to "*", then it works.
Example,
set-item wsman:\localhost\Client\TrustedHosts "*"
ENTER-PSSession -Computer fc00:10:114:247:44d1:f91f:2ceb:b032 -Credential name
> hostname
// Returns SLO-2K8R2-64-5
// IPConfig also returns fc00:10:114:247:44d1:f91f:2ceb:b032 -
Import-Pssession is not importing cmdlets when used in a custom module
I have a PowerShell script/function that works great when I use it in my PowerShell profile or manually copy/paste the function in the PowerShell window.
I'm trying to make the function accessible to other members of my team as a module. I want to have the module stored in a central place so we can all add it to our PSModulePath.
Here is a copy of the basic function:
Function Connect-O365{ $o365cred = Get-Credential [email protected] $session365 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUrihttps://ps.outlook.com/powershell/ -Credential
$o365cred -Authentication Basic -AllowRedirection Import-PSSession $session365 -AllowClobber }
If I save this function in my PowerShell profile it works fine. I can dot source a *.ps1 script with this function in it and it works as well.
The issue is when I save the function as a *.psm1 PowerShell script module. The function runs fine but none of the exported commands from the Import-PSSession are available. I think this may have something to do with the module scope.
I'm looking for suggestions on how to get around this.
I've posted this on www.stackoverflow.com as well but unfortunately haven't had any luck finding a solution.Hi,
As we know there are some kind of powershell profile:
You can have four different profiles in Windows PowerShell. The profiles are listed in load order. The most specific profiles have precedence over less specific profiles where they apply.
%windir%\system32\WindowsPowerShell\v1.0\profile.ps1
This profile applies to all users and all shells.
%windir%\system32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1
This profile applies to all users, but only to the Microsoft.PowerShell shell.
%UserProfile%\My Documents\WindowsPowerShell\profile.ps1
This profile applies only to the current user, but affects all shells.
%UserProfile%\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
This profile applies only to the current user and the Microsoft.PowerShell shell.
What happen when you save it in the first path.
In addition, please also refer to the below links:
Windows PowerShell Profiles
http://msdn.microsoft.com/en-us/library/windows/desktop/bb613488(v=vs.85).aspx
Understanding the Six PowerShell Profiles
http://blogs.technet.com/b/heyscriptingguy/archive/2012/05/21/understanding-the-six-powershell-profiles.aspx
Regards,
Yan Li
Cataleya Li
TechNet Community Support -
Get-DfsrBacklog cmdlet doesn't work from remote computer (pssession)
Hi there!
I try to manage our Server 2012 R2 boxes from a Windows 7 remote machine using PowerShell. For some reason the cmdlet "Get-DFSRbacklog" seems not working remotly. The same cmdlet work when logging in locally to the server(s) with the
same credentials. UAC is turned off on the target machines and i have local admin permissions on this servers using my domain account.
What i do is:
Enter-PSSession <servername>
Get-DfsrBacklog -SourceComputerName <servername> -DestinationComputerName <servername>
Then i receive the following error:
Get-DfsrBacklog : Could not retrieve the backlog information. Replication group: "*" Replicated folder: "*" Source
computer: <servername> Destination computer: <servername> Confirm that you are running in an elevated Windows PowerShell
session and are a member of the local Administrators group on the destination computer. The destination computer must
also be accessible over the network, and have the DFSR service running. This cmdlet does not support WMI calls for the
following or earlier operating systems: Windows Server 2012. Details: WinRM cannot process the request. The following
error with errorcode 0x8009030e occurred while using Kerberos authentication: A specified logon session does not
exist. It may already have been terminated.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or
use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config.
+ CategoryInfo : ProtocolError: (zursf1003:String) [Get-DfsrBacklog], DfsrException
+ FullyQualifiedErrorId : Get-DfsrBacklog.CimException,Microsoft.DistributedFileSystemReplication.Commands.GetDfsr
BacklogCommand
Any ideas?This article
suggests that you're logged into your Win7 management machine with local credentials. You should try the Get-DfsrBacklog command with domain credentials:
Client is in a domain: Attempting to connect to a remote server by using implicit credentials that are the local administrator's credentials on the client. Instead, use domain credentials that are recognized by the domain of the target server, or right-click
the server entry in the Servers tile, click Manage As, and then specify credentials of an administrator on the target server.
Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) _________________________________________________________________________________
Powershell: Learn it before it's an emergency http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx -
Best way to give restricted execute access on pssession to remote user on a server
we have some windows 2008 R2 development environment servers. On these servers we are planning to provide access to developers via PSremoting. We want to restrict the users in such a way that they can only run .bat files present in a certain UNC path. What
is the best way to achieve the same. Can we create a PSSession Configuration for this?
Please note that we are planning to enable WSmanCredSSP on client (it is already enabled on server).
Also, is it possible to give such an access where user can only login to server using powershell's PSsession and not through interactive remote desktop connection.
ApoorvaWHi ApoorvaW,
If you want to setup a restricted pssession, please try to set the session configuration with the cmdlet:
Register-PSSessionConfiguration
Securing Session Configurations
You can assign session configurations to users automatically. For example, you may want to restrict the commands in a session that are available to some users. This is done in a two-step-process:
1. Create a new session configuration that restricts the session to only a subset of commands.
2. Change security access permissions so that the intended users can only access the new session configuration.
For more detailed information about restricted session and paremoting security, please refer to these articles:
PowerShell Remoting: How to Restrict User Commands
Restrict Session
If there is anything else regarding ths issue, please feel free to pst back.
Best Regards,
Anna Wang -
Wait for command prompt - Enter-PSSession
Enter-PSSession -ComputerName ServerName
Restart-Service DNS -PassThru
Exit-PSSession
I am trying to restart the DNS Server service on several remote machines using a foreach loop. The problem is the the script does not wait until the command prompt shows up after executing the "Enter-PSSession -ComputerName ServerName".
I have not been able to fine a way to tell the script to wait for the prompt before continuing the script. Thank you for any assistance that can be provided.You can use
Invoke-Command rather than entering a PS-Session.
Something like this may do what you need:
$servers = @("Server1.fqdn.example.com","Server2.fqdn.example.com","Server3.fqdn.example.com")
$scriptblock = "Restart-Service DNS"
foreach ($server in $servers) {
Invoke-Command -ScriptBlock $scriptblock -ComputerName $server
Replace the server names in $servers with your actual server names. This assumes of course you have PSRemoting enabled which you would need for the PSSessions.
Jason Warren
@jaspnwarren
jasonwarren.ca
habaneroconsulting.com/Insights -
Loading modules when using enter-pssession
Hello
I see some thing that appears unusual to me.
Server1 is running PowerShell v2
Client1 is running PowerShell v2
If I am logged directly to Server1 and do
$Host
$PSVersionTable
I get the result I would expect e.g. version 2 and PSVersion2. I can also load Modules in the normal way directly from Server1 e.g. Import-Module ...
From Client1 (or any other client) if I Enter-PSSession Server1 then
$Host
$PSVersionTable
I get the following verion 1 and PSVersion 2
So basically even though the PSVersion is 2 the Host (e.g. PS-Session Host) is version 1, and therefore I cannot load Modules as I get the following error if I try
Import-Module : The current PowerShell host is: 'ServerRemoteHost' (version 1.0.0.0). The module
'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\pspki\pspki.psd1' requires a minimum PowerShell ho
st version of '2.0' to execute.
So it occurs to me the "Host" execution environment you get with PS-Session is a cut down version e.g. version 1
Is this normal? is there a work around for it?
Thanks All
AAnotherUser__
AAnotherUser__What is a client system? YOu say "client1" which is some PC that is not a "server class" PC is running PowerShell V2. What does that mean.
At any V2 system prompt this is what V2 displays:
PS C:\scripts> $host
Name : ConsoleHost
Version : 2.0
InstanceId : 5bfce22c-8b10-4c67-8dd7-435ff1c351a7
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
PS C:\scripts> $psversiontable
Name Value
CLRVersion 2.0.50727.3655
BuildVersion 6.0.6002.18111
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
Host will report Version 2.0 if it doesn;t you are not running V2 you are running V1.
¯\_(ツ)_/¯ -
Peoplesoft adapter - Failed to execute PSSession request
I am able to make login to PSFT Instance. When I click to child link "Component Interfaces" it not showing anything on the right hand side of the page. The error in the logs is as below:
Thread[AWT-EventQueue-0,6,main] [error] [IWAF JCA] [container] [PeopleSoft.service_PSFT_DevInstance] java.lang.Exception: Not Authorized (90,6)Failed to execute PSSession request Cannot find Component Interface {IWY_CI_ATTRIBUTES} (91,2)
Can anybody please help me on this ?Looking at the stack, it appears to be problem with security configuration on Peoplesoft interfaces
http://download.oracle.com/docs/cd/B31017_01/integrate.1013/b28997/comp_interface.htm -Refer to section Securing a Component Interface to confirm if required steps are performed.
Manoj -
Issues connecting remote server using PSSESSION
Hi All,
I need to execute powershell on servers behind firewall, i set server to use 8530 port (which we opened for patching) so i can reach DMZ server from Non-DMZ via 8530.
Below commands Configured on DMZ Server
Set-Item WSMan:\localhost\Service\EnableCompatibilityHttpListener -Value true
Set-Item wsman:\localhost\listener\listener*\port –value 8530
set-item wsman:\localhost\Client\TrustedHosts -value (non-dmz desktop from where i plan to run Powershell script)
While executing the below command
New-PSSession -ComputerName " IP" -Port 8530 -credential $cred
i am getting following error
Connecting to remote server failed with the following error message : The WinRM client cannot process th
e request. Default authentication may be used with an IP address under the following conditions: the transport is HTTPS
or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure Trus
tedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more information on how to set T
rustedHosts run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting He
lp topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportExc
eption
+ FullyQualifiedErrorId : PSSessionOpenFailed
If i execute with NAME
Invoke-Command -ComputerName HAMWINWIZP015 -ScriptBlock {Get-Process} -Credential $cred
Connecting to remote server failed with the following error message : WinRM cannot process the request.
The following error occured while using Kerberos authentication: The network path was not found.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or us
e HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information,
see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
Could you suggest what would be the issue & if possible please help me to use that DMZ Server as proxy server as i am willing to run powershell on few DMZ Server via the one server.
GanapathyHi Ganapathy,
I am trying to involve someone familiar with this topic to further look at this issue.
There might be some time delay. Appreciate your patience.
If you have any feedback on our support, please click here.
Best Regards,
Anna
TechNet Community Support -
Granfeldt PowerShell MA Import-PSSession?
Firstly
Søren Granfeldt thank you for writing and releasing this MA! I'm using it for Account Expiration dates already!! My issue is when trying to connect to Exchange Online (O365) to manage mailboxes.
I'm using the Granfeldt PowerShell MA to access data in Office 365 but not just the dirsync (is the user licensed) but also properties on the Exchange Online.
I can connect to Exchange Online (O365) when running the script as the service account (FIMService). It connects using stored credentials to Exchange Online using Remote PowerShell and Importing the session with -AllowClobber. However I get an error
on the Import-PSSession line saying that $Session is undefined / Null when the MA Runs it.
I have a couple of questions.
1) If I edit the import.ps1 script (Import Script) do I need to refresh the PowerShell MA Schema for it to pick up the changes or does it load and run this on the fly?
2) Has any one ran an Import-PSSession with the Granfeldt PowerShell and gotten a script Error: Script error in line 24: [Cannot validate argument on parameter 'Session'. The argument is null. Supply a non-null argument and try the command again.]
- (At {REMOVED}
+ Import-PSSession -Session $mySession -AllowClobber -WarningAction SilentlyCo ...
The error is under the $mySession variable, it should connect just fine, I've gone so far as hard coding the password into the script.
3) Is there any way to make the import script "Run as Admin / Elevated" ?
Thanks in advance!!!!
Jonathan ManleyI was able to make a test against Exchange Online. The below Import.ps1 works fine in Sorens PS MA.
param (
$Username,
$Password
#Create Session
$pw = ConvertTo-SecureString -AsPlainText -Force -String $Password
$O365Credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $Username,$pw
$session = New-PSSession -ConfigurationName "Microsoft.Exchange" -ConnectionUri "https://ps.outlook.com/powershell" -Credential $O365Credentials -Authentication Basic -AllowRedirection
$result = Import-PSSession $session -AllowClobber -CommandName Get-MailUSer
$MailUsers = Get-MailUser
ForEach($MailUser in $MailUsers)
$obj = @{}
$obj.Add("Alias",$MailUser.Alias)
$obj.Add("objectClass", "MailUser")
$obj
Kent;
Thank you for the script. I created a new import script with just the code here in the post by itself. I still get the following error in the Logs (Turned the logs on using the Registery key per Soren's blog post.)
I'm just including one line above the error and one line below the error. Let me know if more would help.
It's like for some reason the remote PowerShell session doesn't get connected.
4/21/2014 7:48:47 PM: Should impersonate: True
4/21/2014 7:48:50 PM: Script error in line 11: [Cannot validate argument on parameter 'Session'. The argument is null. Supply a non-null argument and try the command again.] - (At C:\Office365-MA\O365Import2.ps1:11 char:28
+ $result = Import-PSSession $session -AllowClobber -CommandName Get-MailUSer
+ ~~~~~~~~)
4/21/2014 7:48:50 PM: Script error: [ps.outlook.com] Closing remote server shell instance failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
4/21/2014 7:48:50 PM: Page token returned: '' -
Execute commands remote with PSSession
Hi,
I am trying to write a script that is executed on Server A but connects to Server B and executes the commands with remote Powershell.
I am currently just trying some simple commands since it's the first time I have tried the remote Powershell function. I connect to a server which is working fine, but if I do a simple command like:
$FoundFiles = Get-ChildItem - Path "C:\Temp"
it returns an error telling me that it cannot find the path. If I do the same and use "C:\Windows" it works.
If I enter the commands manually in a console everything also works as expected.
Lasse
/LasseIf you do this:
Enter-PSSession -Name TestConnection
$tmpFiles = get-childitem -path "C:\temp"
you will be running from the remote system and c:\temp will have to be on the remote system. Either copy the file there or use invoke.
Spend some time testing the commands until you sort out how remoting works. When you enter a sessin your prompt changes to tell you you are now running on the remote system and all references are to the remote system.
This works the same but references are local and execution is remote:
$session=New-PSSession -ComputerName Servername
invoke-command -file c:\temp\script.ps1 -Session $session -ArgumentList '-param1 xxxx','-param2 vvvvv'
I can also alter the session:
PS C:\scripts> invoke-command -command {$newvar='hello remote'} -Session $session
PS C:\scripts> invoke-command -command {$newvar} -Session $session
hello remote
Notice the session is retained. I can load modules in one command or file and use them in another:
We can also use -AsJob for very long running scripts and invoke against a list of computers.
it is not just a telnet like session but a full remote targetable session.
¯\_(ツ)_/¯ -
os 2008 R2 sp2
I have disabled UAC completely , confirmed this by launching a standard cmd prompt and cd C:\Windows\SysWOW64\config
as per http://blog.pythonaro.com/2013/05/fully-disable-user-access-control-uac.html
When i run the following , nothing happens , as i am running psexec , this is not the double hop issue , the files make it to the server.
I am attempting to run a local exe on the target server , the psexec is simply to run the copy command , the double hop has been sorted and the files make it to the local server
the exe does not kick off but does when i enter the session interactive and run the exe call and arg
$complist =@("server1","server2")
$server = "sourcefileserver"
function NewLogin($computer)
$session = new-pssession -computername $computer -Authentication Kerberos
return $session
Function Func_installSoft($Computer)
$session = NewLogin $Computer
$scriptblock={
c:\install\vcredist_x64.exe /passive
Invoke-Command -session $session -ScriptBlock $scriptblock
Remove-PSSession -session $session
foreach($element in $complist)
psexec \\$element -s robocopy "\\$server\Documents\install\" "c:\Install"
Func_installSoft $element
If i run the following interactively , the install runs fine , Logically i am doing exactly the same thing right?
$comp = "qual29web001"
$session = new-pssession -computername $comp -Authentication Kerberos
$sessions = get-pssession
$sessionid = $sessions.ID[0]
enter-pssession $sessionid
c:\install\vcredist_x64.exe /passive
exit
remove-pssession *
Any help is much appreciated , the install is a rollup for visual studioin the interest of fixing this issue for other users
context: install executables and windows hotfix's
dependancies: psexec , uac disabled as per , enable psremoting
http://blog.pythonaro.com/2013/05/fully-disable-user-access-control-uac.html
regards
A person who cobbles together "WORKING SCRIPTS"
$complist =@("server1","server2")
Function New-RemoteProcess {
Param([string]$computername=$env:computername,
[string]$cmd=$(Throw "You must enter the full path to the command which will create the process.")
$ErrorActionPreference="SilentlyContinue"
Trap {
Write-Warning "There was an error connecting to the remote computer or creating the process"
Continue
Write-Host "Connecting to $computername" -ForegroundColor CYAN
Write-Host "Process to create is $cmd" -ForegroundColor CYAN
[wmiclass]$wmi="\\$computername\root\cimv2:win32_process"
#bail out if the object didn't get created
if (!$wmi) {return}
$remote=$wmi.Create($cmd)
if ($remote.returnvalue -eq 0) {
Write-Host "Successfully launched $cmd on $computername with a process id of" $remote.processid -ForegroundColor GREEN
else {
Write-Host "Failed to launch $cmd on $computername. ReturnValue is" $remote.ReturnValue -ForegroundColor RED
foreach($element in $complist)
psexec \\$element -s robocopy "\\filelocationserver\Documents\install\" "c:\Install"
Start-Sleep -s 10
psexec \\$element -u domain\user -p password Expand –F:* c:\install\Windows6.1-KB2554746-v2-x64.msu c:\install\
psexec \\$element -u domain\user -p password DISM.exe /Online /Add-Package /PackagePath:c:\install\Windows6.1-KB2554746-v2-x64.cab /Quiet /NoRestart
New-RemoteProcess -comp $element -cmd "c:\install\vcredist_x64.exe /passive"
New-RemoteProcess -comp $element -cmd "c:\install\vcredist_x86.exe /passive" -
PSSESSION issues with powershell. Wierd result
Hi
I have a problem, the problem is that I am running a PowerShell script:
$server
= get-ADComputer -Filter 'Name -like "serv*"' | select name
$server
| ForEach-Object { Enter-PSSession -ComputerName $_.name import-module servermanager add-WindowsFeature XPS-Viewer Exit-PSSession }
And I'm getting the result of:
Success Restart Needed Exit Code Feature Result
True No NoChan... {} (that's because I have run it several times) but the initial was "true" "no" and "successful"
when I run get-windowsfeature xps-viewer, I get this:
Display Name Name
[X] XPS Viewer XPS-Viewer
That means that xps is installed, BUT IT IS NOT INSTALLED!!!
If I run pssession directly to the server(in powershell window)(001->) it works! see further:
"PS C:\Windows\system32> enter-pssession -computername server071"
[server071]: PS C:\Users\4x\Documents> import-module servermanager
[server071]: PS C:\Users\4x\Documents> get-windowsfeature xps-viewer
Display Name Name
[ ] XPS Viewer XPS-Viewer
Its not installed!!
now I run from powershell:
[server071]: PS C:\Users\4x\Documents> add-windowsfeature xps-viewer
Success Restart Needed Exit Code Feature Result
True No Success {XPS Viewer}
WHAT AM I DOING WRONG? It seems hopeless, I have about 500+ servers, and doing this manual is not an option! I have done variations, like just using 1 server name, but the result is the same. no installation, but the result says "ok, done" no error, BUT IT HAS NOT INSTALLED!!
Please I need some advice here... HELP!!!!
PS: Running from POWERGUI in ADMIN mode..
JFBEnter-PSSession is for interactive session.....if you want a scriptblock to be executed on a remote mcahine use Invoke-Command:
$server= get-ADComputer -Filter 'Name -like "serv*"' | select name
$server | ForEach-Object { Invoke-Command -ComputerName $_.name -scriptblock {import-module servermanager;add-WindowsFeature XPS-Viewer }
EDIT-- Oops looks like it's already answered
Hope this helps
Knowledge is Power{Shell}. -
Hello
I need to copy files over the network PSSession . ( Firewall / DMZ / Etc. )
I have a script where I copy from my local server ( server1) to the remote server ( server2 ), but I can´t not make script that will copy from the remote server to my local by my session. From server2 to server1
Script is as below ...:-)
HELP : ....
winrm s winrm/config/client '@{TrustedHosts="SERVER2"}'
$Source = "D:\test\ok.log"
$Destination = "D:\test\ok.log"
$session = New-PSSession -ComputerName SERVER2
Set-StrictMode -Version Latest
## Get the source file, and then get its content
$sourcePath = (Resolve-Path $source).Path
$sourceBytes = [IO.File]::ReadAllBytes($sourcePath)
$streamChunks = @()
## Now break it into chunks to stream
Write-Progress -Activity "Sending $Source" -Status "Preparing file"
$streamSize = 1MB
for($position = 0; $position -lt $sourceBytes.Length;
$position += $streamSize)
$remaining = $sourceBytes.Length - $position
$remaining = [Math]::Min($remaining, $streamSize)
$nextChunk = New-Object byte[] $remaining
[Array]::Copy($sourcebytes, $position, $nextChunk, 0, $remaining)
$streamChunks += ,$nextChunk
$remoteScript = {
param($destination, $length)
## Convert the destination path to a full filesytem path (to support
## relative paths)
$Destination = $executionContext.SessionState.`
Path.GetUnresolvedProviderPathFromPSPath($Destination)
## Create a new array to hold the file content
$destBytes = New-Object byte[] $length
$position = 0
## Go through the input, and fill in the new array of file content
foreach($chunk in $input)
Write-Progress -Activity "Writing $Destination" `
-Status "Sending file" `
-PercentComplete ($position / $length * 100)
[GC]::Collect()
[Array]::Copy($chunk, 0, $destBytes, $position, $chunk.Length)
$position += $chunk.Length
## Write the content to the new file
[IO.File]::WriteAllBytes($destination, $destBytes)
## Show the result
Get-Item $destination
[GC]::Collect()
## Stream the chunks into the remote script
$streamChunks | Invoke-Command -Session $session $remoteScript `
-ArgumentList $destination,$sourceBytes.Length
Remove-PSSession -Session $sessionBut have will the script look, if i need to copy from
From server2 to server1.
My script copy from server1 to server2 and working, but I need server2
to server1.
Maybe you are looking for
-
Start Routine not working correctly.
Hi gurus, I'm having a problem with a start routine in an update rule to one of my cubes. I debug it and it seems to work fine. However, it ends the simulation saying in the error message "No active update rules exist for this infosource." However, I
-
Where to find adapter: old iMac speakers to MacBook Pro
Was a great set of Speakers on old iMac, but the plug is too small for MacBook Pro. Tried Radio Shack, but their's didn't work. Not a geek, but frugal and I hate to just discard some decent speakers. Anyone else deal with this or suggest a source to
-
Lots of warnings when upgrading ghc and haskell libraries
Heres the list of packages I upgraded today: cups 1.5.3-4 1.5.3-5 -0.73 MiB 6.87 MiB ghc 7.4.1-2 7.4.2-1 6.09 MiB 60.13 MiB haskell-mtl 2.0.1.0-4 2.1.1-1 0.43 MiB 0.19 MiB haskell-random 1.0.1.1-1 1.0.1.1-2 -0.05 MiB 0.29 MiB haskell-syb 0.3.6-1 0.3.
-
Material Determination -SAP SD
Hi All, I am working in Material Deterimination ( based on ATP). for eg: if the Product X is 10 QTY , when i create the sales order for Product X for 20 qty , system should pick 10 from X and remaining 10 from Y ( which we mentioend in COndition reco
-
Programmatically load fragment
Hello, I was looking for a way to load fragment dynamically (actually fragment associated with a service. This service can be started (fragment displayed) or not (fragment hidden) in a configuration window). With the help of bsd (thanks to him) on IR