Invoke-command for msiexec hangs

Hi,
I'm running a client of Windows 8 Pro against a server of Win2012R2
I have the following script:
  $args = "-i `"$MSIPathFile`" INSTALLDIR=`"$InstallFolderOnTargetServer`" /qn /norestart"
        LogInfo "args: $args"
        $Session = EstablishSession $TargetServer $CommonPowershellScriptPath
        try
            #Invoke-Command -session $Session -ScriptBlock{param($arguments) start-process -FilePath "msiexec.exe" -Wait $arguments } -Argument $arguments
            #winrs -r:$TargetServer msiexec.exe $arguments
            $script = {
                #do preinstall stuff
                [diagnostics.process]::start("c:\windows\system32\msiexec.exe", $args).WaitForExit()
                #do follow up stuff
            invoke-command -session $Session -scriptblock $script
When the invoke-command line is executed, I get no response - I've waited for 10 minutes!
I've checked the event log on the server and client and there's nothing. I know the $Session variable holds a good session because it works with this elsewhere in the script. The credential used by this is a domain account that is a member of the local administrators
group on the target server
If I take the content of $args and run this with msiexec directly on the server then the msi silently installs in about 15 seconds.
I have followed the instructions here in order to Enable-PsWsmanCombinedTrace (http://windowsitpro.com/blog/troubleshooting-winrm-and-powershell-remoting-part-1) but
the only error I see is within the "Windows Remote Management\Operational" log:
WSMan operation SignalShell failed, error code 2150858793
I think this could be caused when I force the debugger to stop - so could be a red herring.
This same script has worked well in the past, though that was different servers and network.
Any suggestions as to what else I can try in order to get the MSI to install remotely?

Not all MSIs will install unattended.  It is pretty certian a message is being shown and stoipping the install.  Check with the vendor to be sure they support full unattended installs.
¯\_(ツ)_/¯

Similar Messages

  • Certreq -submit run locally returns successful but run remote via invoke-command hangs

    Good morning I have been struggling with a certificate request script.
    The requesting server is in the dmz and I have a management server internally.
    I successfully create the Inf file, as well as the req file then copy the req file to my internal management server. Once copied internal I attempt to run the following command from my laptop executing as my admin account
    $Fqdn = "server.dmz.com"
    $managementServer = "InternalServer"
    $Path = "C$\Test\CertRequests"
    Invoke-Command -ComputerName $Managementserver -ScriptBlock {param($CertificateAuthority,$FQDN,$Managementserver,$Path) certreq.exe -submit -attrib "CertificateTemplate:DVNOfflineComputer" -config "$CertificateAuthority" "\\$Managementserver\$Path\$FQDN.req" "\\$Managementserver\$Path\$FQDN.crt"} -ArgumentList $CertificateAuthority,$FQDN,$Managementserver,$Path
    This exact command pasted into a powershell window locally on the management server returns the crt file.
    Run via invoke-command just hangs forever. I even tried to the Silent=True in inf file as well as -q but neither worked.
    Any help is greatly appreciated.

    Hi Jason,
    I reform the script as below, and add the "test-path" to check if the .req and .crt files exist, please also note you haven't assign value to the "$CertificateAuthority" variable:
    $Fqdn = "server.dmz.com"
    $managementServer = "InternalServer"
    $Path = "C$\Test\CertRequests"
    $CertificateAuthority = "something"
    $script={
    param($CertificateAuthority,$FQDN,$Managementserver,$Path)
    test-path "\\$Managementserver\$Path\$FQDN.req"
    test-path "\\$Managementserver\$Path\$FQDN.crt"
    certreq.exe -submit -attrib "CertificateTemplate:DVNOfflineComputer" -config $CertificateAuthority "\\$Managementserver\$Path\$FQDN.req" "\\$Managementserver\$Path\$FQDN.crt"
    Invoke-Command -ComputerName $Managementserver -ScriptBlock $script -ArgumentList $CertificateAuthority,$FQDN,$Managementserver,$Path
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • Invoke-command takes 20-90 seconds to complete

    all servers I'm testing with is server 2008r2 with powershell 4.  I have a text file with 100 servers that are online and with PS remoting enabled.
    When I run this command:
    # this takes about 20-30 seconds to complete
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    # this takes at least 90 seconds to complete when I set throttle to 100
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    -ThrottleLimit
    100
    I didn't get these delays when my local was running powershell 2 and executing against the same set of servers with PS4 on them.  PS2 only took 2-3 seconds to finish the command if all were online.  If I run the command in PS4 ISE, it seems to
    work fast as well but for some reason PS4 traditional shell (not ISE) gives me these delays when working with large set of servers and increasing throttle to 100+
    Sometimes you get different results if you keep running it with the same shell, but if you open a new shell with -noprofile switch then I get the same execution delays with PS4.
    # I even tried skipping the different checks with sessionOption below but same results
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    -ThrottleLimit
    100
    -SessionOption
    (New-PSSessionOption
    -SkipCACheck
    -SkipRevocationCheck
    -SkipCNCheck)
    I also tried running the same command from win8.1 with PS4 and it will hang for about 90 seconds before it spits out all the results at once.
    This seems to be a problem with large number of servers of at least 50.  Works fine with small set.  Is anyone else having this problem?  I know there's other ways of running scripts in parallel, but I can't figure out why this is not working. 
    I'm also using the default pssessionoption below.  I have full admin rights to all the servers.  Any suggestions?
    MaximumConnectionRedirectionCount : 5
    NoCompression                     : False
    NoMachineProfile                  : False
    ProxyAccessType                   : None
    ProxyAuthentication               : Negotiate
    ProxyCredential                   :
    SkipCACheck                       : False
    SkipCNCheck                       : False
    SkipRevocationCheck               : False
    OperationTimeout                  : 00:03:00
    NoEncryption                      : False
    UseUTF16                          : False
    IncludePortInSPN                  : False
    OutputBufferingMode               : None
    Culture                           :
    UICulture                         :
    MaximumReceivedDataSizePerCommand :
    MaximumReceivedObjectSize         :
    ApplicationArguments              :
    OpenTimeout                       : 00:03:00
    CancelTimeout                     : 00:01:00
    IdleTimeout                       : -00:00:00.0010000

    -asjob only puts it in the background, but it still takes the same amount of time to finish.  Any other suggestions?  I want to be able to increase the throttle to at least 100 servers.  With PS2, I was able to throttle to 200 servers and
    was very fast.  Not sure why PS4 is so much slower.  It seems to run better without increasing the throttle, but still slower when dealing with 100 servers compared to PS2 results.
    Invoke-Command
    -ScriptBlock
    {get-date}
    -ComputerName
    (gc
    100servers.txt)
    -ThrottleLimit
    100

  • Invoke-Command - SQL collation change function

    Hi,
    I am creating a script to automatically configure SQL servers in Azure from one of the base Azure SQL VM templates. All of my code works well besides changing the default collation of the instance. The PowerShell code works but the problem is that the
    command only runs the setup.exe command correctly if I have an open RDP session to the server. I'm trying to figure out why it won't run without the RDP session and either work around it or change the code to something that will work consistently. For
    now, I have it open an RDP session but this method won't work in future when I fully automate the scripts.
    Here is my code for the ChangeCollation function:
    FUNCTION ChangeCollation
    param
    [Parameter(Mandatory=$true)]$DeploymentName,
    [Parameter(Mandatory=$true)]$AdminName,
    [Parameter(Mandatory=$true)]$AdminPassword,
    [Parameter(Mandatory=$true)]$Collation
    Write-Host ("Rebuilding instance collation, setting to $Collation ... ") -ForegroundColor Green
    $setup = (Start-Process -FilePath "C:\SQLServer_12.0_Full\Setup.exe" -ArgumentList "/QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=$DeploymentName\$AdminName /SAPWD=$AdminPassword /SQLCOLLATION=$Collation" -NoNewWindow -Wait -PassThru).ExitCode
    If ($setup -eq 0) { Write-Host ("Successfully set collation to $Collation") -ForegroundColor Green}
    If ($setup -ne 0) { Write-Host ("Failed to set collation to $Collation") -ForegroundColor Red}
    I execute it as follows, its in a basic retry loop which tries restarting the services or server if the command fails:
    try
    Invoke-Command -ConnectionUri $uri.ToString() -Credential $credential -ScriptBlock ${function:ChangeCollation} -ArgumentList $DeploymentName, $AdminName, $AdminPassword, $Collation
    $NewCollation = Invoke-Command -ConnectionUri $uri.ToString() -Credential $credential -ScriptBlock {Invoke-SQLCmd "SELECT CONVERT (varchar, SERVERPROPERTY('collation'));"}
    $NewCollation = $NewCollation.Column1
    If ($Collation -ne $NewCollation)
    Throw "Collation not changed exception!"
    $Stoploop = $true
    }Catch{ .......}
    If I have an RDP session open as the local admin which is the same account as I am running the invoke-command with, the setup.exe runs through just fine. Without an RDP session, Invoke waits a minute or two then exits. I can see from the logs on the server
    it hasn't tried to change the collation of the instance.
    I've tried additional switches on the start-process, like -LoadUserProfile or without -nonewwindow but they made no difference. I have also tried changing the collation with the command sqlservr, seems to work sometimes but its inconsistent
    and I don't get the returned result saying that it completed successfully so the code just hangs even after the change.
    Does anyone have any idea why an exe wouldn't work via an invoke without the RDP session? Or alternatively a better way to change the collation of the database which is consistent?

    Hi Federico,
    As Ashwin’s post, before changing server level collation, please check that if the existing SQL Server collation setting of your instance is ‘SQL_Latin1_General_CP1_CI_AS’ with the command below.
    SELECT SERVERPROPERTY(N'Collation')
    Then perform the following steps to change the server level collation and put new collation value.
    1. Record all server-wide configuration values by running the below commands and save the output.
    SELECT * FROM sys.configurations;
    -- OR
    EXEC SP_CONFIGURE
    2. Create and prepare all scripts related to jobs, maintenance plans, logins and their access levels.
    3. Detach all user databases before rebuilding your system databases.
    4. Run your original scripts to rebuild the system databases. Make sure to run this command from the directory where you have placed your SQL Server setup files.
    5. Check the server collation to verify whether this change is successful or not by running the command “SELECT SERVERPROPERTY(N'Collation') ”
    6. Attach all user databases which were detached in Step 3.
    7. Change the collation settings of all user databases.
    ALTER DATABASE DBName collate <NewCollation>
    8. Run all of the which were created in Step 2 to restore jobs, alerts, logins, operators scripts and so on.
    For more details, please review the following blog.
    How to change server level collation for a SQL Server Instance http://www.mssqltips.com/sqlservertip/2901/how-to-change-server-level-collation-for-a-sql-server-instance/
    Thanks,
    Lydia Zhang
    Lydia Zhang
    TechNet Community Support

  • Powershell - Invoke-Command Network Connection has been interrupted

    Hi,
    I have been having this problem intermittently, i use
    invoke-command -AsJob -computername myserver1 -scriptblock {get-process}
    WARNING: The network connection to myserver1 has been interrupted. Attempting to reconnect for up
    to 4 minutes...
    WARNING: Attempting to reconnect to myserver1 ...
    WARNING: The network connection to myserver1 has
    been restored.
    On another window i did a ping myserver1 -t to see if any network packets are lost but anything of that sort happened.
    I tried using the IP of myserver1 as well and see the same.
    Any idea why this message comes up and under what circumstances?
    Thanks for your thoughts and help.

    Hi Past,
    this sounds like a temporary lack of access to the necessary remote resources. Direct network connectivity is of course mandatory, but there are more dependencies. Pinging will still work when the WinRM service hangs, local Powershell Execution on the target
    is on hold, massive lack of available resources, etc..
    I do not know of any specifically typical reasons for this to occur, so the only recommendation I can give you is to do some more in depth monitoring on the target device while recreating the issue.
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • Error occurred in deployment step 'Add Solution': A timeout has occurred while invoking commands in SharePoint host process.

    Hi,
    I am deplyoing a  solution which has  custom web parts- vwp- appln pages, event receivers.
    It was working fine till last week. I was able to deploy the solution and able to see the web parts and func. was working.
    But now from the last 2 days onwards, when I tried to depoy this soution, I am getting the error
    "Error occurred in deployment step 'Add Solution': A timeout has occurred while invoking commands in SharePoint host process "
    may i know why am getting this error.
    note: my dev machine- Win Srvr 2012 - VS 2012- SP 2013 - SP D 2013 was having soem issues  with the space in C drive.
    once i have done the  index reset few months back and i started getting space in C:\ Drive is 0 bytes.
    so what my infra. team  has done is , increased the space in drive to 150 GB[ it was a  VM ].
    help is appreciated !

    What is current disk space on your drives
    Delete ULS logs and other log files from server id not needed
    could be related to ChannelOperationTimeout
    http://msdn.microsoft.com/en-us/library/ee471440(v=vs.100).aspx
    Also, don't forget to restart Visual Studio
    Goto the following regustry key: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\SharePointTools
    Add the following as a DWORD (wont be there by default)
    ChannelOperationTimeout
    REG_DWORD that specifies the time, in seconds, that Visual Studio waits for a SharePoint command to execute. If the command does not execute in time, a SharePointConnectionException is thrown.
    The default is 120 seconds.
    http://social.technet.microsoft.com/wiki/contents/articles/21052.como-resolver-o-erro-error-occurred-in-deployment-step-activate-features-a-timeout-has-occurred-while-invoking-commands-in-sharepoint-host-process-pt-br.aspx
    If this helped you resolve your issue, please mark it Answered

  • Error occurred in deployment step 'Activate Features': A timeout has occurred while invoking commands in SharePoint host process.

    Error 1 Error occurred in deployment step 'Activate Features': A timeout has occurred while invoking commands in SharePoint host process.
    0 0 myProjectAssetsLists
    am getting the above error when i deploy my farm solution which is actually a "farm solution import package" template.
    i am deploying this to a new site collection and once its features are activated this will provision few doc libs and splists in the targeted site.
    any help is appreciated.

    try below link:
    http://msdn.microsoft.com/en-us/library/ee471440.aspx
    http://sujeetrec.blogspot.in/2013/12/sharepoint-2010-deployment-timing-out.html
    Increase the timeout that Visual Studio waits for SharePoint to deploy a feature:
    Create: [HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\SharePointTools] ChannelOperationTimeout DWORD
    The value is a timeout in seconds. The default is 120 (2 minutes).
    Full details on this switch and others are here:
    http://msdn.microsoft.com/en-us/library/ee471440.aspx

  • A communication error has occurred while invoking commands in SharePoint host process

    Hi All,
    I am using Virtual box to connect to Sharepoint 2013 VPC. Due to an unexpected sutdown of my machine the VPC got some issue. Now I restored it using my bak up file. But after this when I deploy my sharepoint 2013 farm solution Iam getting the following error.
    Error occurred in deployment step 'Recycle IIS Application Pool': A communication error has occurred while invoking commands in SharePoint host process: The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature
    session shutdown or an internal server error.
    What could be the issue? Any suggestions ?
    Thanks in advance...
    Regards
    Nimisha
    [email protected]

    Hi Nimisha,
    Seems that the original issue of communication error has been solved, for this new issue, it is recommended that you open a new thread which can make others easier
    to focus on one issue in one single thread.
    Best regards,
    Patrick
    Patrick Liang
    TechNet Community Support

  • Run invoke-command on multiple machines at the same time

    Hey all so I read that if I store my New-pssession in a variable then used that in my invoke-command it would run all computers at the same time.
    $a = Get-Content "C:\Users\cody-horton\Desktop\list.txt"
    $session
    for($i=0;$i -lt $a.Length;$i++){
    if(!(Test-Connection -Cn $a[$i] -BufferSize 16 -Count 1 -ea 0 -quiet)){
    Write-Host $a[$i] -foregroundcolor red
    else{
    $session = New-PSSession $a[$i]
    Invoke-Command -Session $session -FilePath "\\My computer\C`$\Users\public\Documents\zip folder.ps1"
    What exactly am I doing wrong I just need to run this script on multiple machines at the same time.
    Thanks.
    Edit: Also what would be the best way to close all the sessions thanks.

    Hi there,
    So what I think you are doing wrong here is that you are overwriting the value in $Session everytime you executed code inside for loop. try the below:
    $a = Get-Content "C:\Users\cody-horton\Desktop\list.txt"
    $session = @() #define this as an array
    for($i=0;$i -lt $a.Length;$i++){
    if(!(Test-Connection -Cn $a[$i] -BufferSize 16 -Count 1 -ea 0 -quiet)){
    Write-Host $a[$i] -foregroundcolor red
    else{
    $session += New-PSSession $a[$i] #add the new session to the array, at the end it will be a collection of sessions
    Invoke-Command -Session $session -FilePath "\\My computer\C`$\Users\public\Documents\zip folder.ps1" #I think the above one won't work..first you need to copy the script locally on the machine and then execute it#Why this won't work because of Second-Hop Authentication
    Have put comments where I edited your code.
    Hope this helps
    Knowledge is Power{Shell}. http://dexterposh.blogspot.com/

  • How can you run a command with elevated rights on a remote server with invoke-command ?

    I am trying to run a script on a remote server with invoke-command.  The script is starting and is running fine, but the problem is that it should be running with elevated rights on the remote server.  On the server where I start the invoke-command, my account has the necessary rights.
    The server were I launch the invoke-command is a W2K8 R2.  The remote box is a W2K3 with powershell v2.0 installed.
    When I launch the script on the remote-box from the command line, I don't get the access denied's.
    Is there a way to do this ?
    Thanks in advance

    The script that I want to run is to install the windows updates.  I get an access denied on the download of the updates.
    When I execute the script on an W2K8 box, (not remotely) and I run it with non-elevated rights, I get the same error.
    The script is running fine when it is launched on W2K3 box locally with a domain account that has local admin rights, or on a W2K8 R2 server with a domain account that has local admin rights, but with elevated rights.
    Thanks in advance for your help.
    #=== start script ====
    param($installOption="TESTINSTALL",$rebootOption="NOREBOOT")
    Function Show-Help
    Write-Host ""
    Write-Host "SCRIPT: $scriptName <installOption> <RebootOption>"
    Write-Host ""
    Write-Host "DESCRIPTION: Installatie van WSUS updates op de lokale server"
    Write-Host ""
    Write-Host "PARAMETERS"
    Write-Host " -installOption <[INSTALL|TESTINSTALL]>"
    Write-Host " -rebootOption <[REBOOT|NOREBOOT|REBOOT_IF_UPDATED]>"
    Write-Host ""
    Write-Host "EXAMPLE:"
    Write-Host "$ScriptName -installOption INSTALL -rebootOption REBOOT_IF_UPDATED"
    Write-Host "$ScriptNAme INSTALL NOREBOOT"
    Write-Host ""
    Write-Host "Indien beide parameter weggelaten worden zijn de defaultwaarden :"
    Write-Host " installOption=TESTINSTALL "
    Write-Host " RebootOption=NOREBOOT"
    Write-Host ""
    Exit
    #Include alle globale variablen
    $CEIF_WIN_PATH = (get-content env:CEIF_WIN_PATH)
    $includeFile=$CEIF_WIN_PATH + "\Scripts\include_win.ps1"
    . $includeFile
    #initialiseer error count
    $errcnt=0
    $scriptName=$MyInvocation.MyCommand.Name
    #argumenten controleren
    $arrInstallOption= "TESTINSTALL", "INSTALL" # Mandatory variable with predefined values
    If (!($arrInstallOption –contains $installOption)){ Show-Help }
    $arrRebootOption = "REBOOT", "NOREBOOT","REBOOT_IF_UPDATED" # Mandatory variable with predefined values
    If (!($arrRebootOption –contains $rebootOption)){ Show-Help }
    #Logfile opbouwen
    $logfile = get-logfileName($MyInvocation.MyCommand.Name)
    Log-scriptStart $MyInvocation.MyCommand.Name $logfile
    function Get-WIAStatusValue($value)
    switch -exact ($value)
    0 {"NotStarted"}
    1 {"InProgress"}
    2 {"Succeeded"}
    3 {"SucceededWithErrors"}
    4 {"Failed"}
    5 {"Aborted"}
    function boot-server()
    if ($installOption -eq "TESTINSTALL")
    logger "TESTINSTALL : - Reboot local Server" $logfile
    else
    logger " - Reboot local Server" $logfile
    $thisServer = gwmi win32_operatingsystem
    $thisServer.psbase.Scope.Options.EnablePrivileges = $true
    $thisServer.Reboot()
    $logmsg="Install option = " + $installOption + ", RebootOption = $rebootOption"
    logger "$logmsg" $logfile
    logger "" $logfile
    logger " - Creating WU COM object" $logfile
    $UpdateSession = New-Object -ComObject Microsoft.Update.Session
    $UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
    logger " - Searching for Updates" $logfile
    $SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
    logger " - Found [$($SearchResult.Updates.count)] Updates to Download and install" $logfile
    $Updates=$($SearchResult.Updates.count)
    logger "" $logfile
    foreach($Update in $SearchResult.Updates)
    if ($Update.EulaAccepted -eq 0)
    $Update.AcceptEula()
    # Add Update to Collection
    $UpdatesCollection = New-Object -ComObject Microsoft.Update.UpdateColl
    $UpdatesCollection.Add($Update) | out-null
    if ($installOption -eq "TESTINSTALL")
    else
    # Download
    logger " + Downloading Update $($Update.Title)" $logfile
    $UpdatesDownloader = $UpdateSession.CreateUpdateDownloader()
    $UpdatesDownloader.Updates = $UpdatesCollection
    $DownloadResult = $UpdatesDownloader.Download()
    $Message = " - Download {0}" -f (Get-WIAStatusValue $DownloadResult.ResultCode)
    if ($DownloadResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    # Install
    logger " - Installing Update" $logfile
    $UpdatesInstaller = $UpdateSession.CreateUpdateInstaller()
    $UpdatesInstaller.Updates = $UpdatesCollection
    $InstallResult = $UpdatesInstaller.Install()
    $Message = " - Install {0}" -f (Get-WIAStatusValue $InstallResult.ResultCode)
    if ($InstallResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    logger "" $logfile
    #Indien er een fout gebeurde tijdens download/installatie -> stuur mail naar windowsteam
    if ( $errcnt -gt 0 )
    logger " - Fout tijdens de uitvoering van script -> send mail" $logfile
    $mailSubject=$MyInvocation.MyCommand.Name
    $msg = new-object Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($logfile)
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = $mailFrom
    $msg.To.Add($mailTo)
    $msg.Subject = $mailSubject
    $msg.Body = “Meer details in attachement”
    $msg.Attachments.Add($att)
    $smtp.Send($msg)
    #Moet de server herstart worden ?
    if ($rebootOption -eq "REBOOT_IF_UPDATED" )
    if ($Updates -gt 0)
    #Reboot the server when updates are installed
    boot-server
    elseif ($rebootOption -eq "REBOOT")
    #reboot the server always
    boot-server
    else
    #Do not reboot the server
    logger "Do not reboot the server" $logfile
    Log-scriptEnd $MyInvocation.MyCommand.Name $logfile
    exit 0

  • Invoke-Command and ShellId Issues

    Hi all,
    I'm struggling to figure out what is going on here.
    I'm trying to add a domain user to a VM's local administrators group via this:
    $localAdminBlock = `
    $objUser = [ADSI]("WinNT://domain/domainaccount")
    $objGroup = [ADSI]("WinNT://$vm/Administrators")
    $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)
    Invoke-Command -ComputerName $vm -Scriptblock $localAdminBlock -Credential $adminCreds
    I receive an error:
    "Processing data from remote server TestServer failed with the following error message: The request for the Windows Remote Shell with ShellId <id here> failed because the shell was not found on the server.  Possible causes are: the specified
    ShellId is incorrect or the shell no longer exists on the server.  Provide the correct ShellId or create a new shell and retry the operation..."
    Any idea what's going on?
    Thanks.

    You need to use $using:vm instead of $vm since you are passing a value from a local variable into the scriptblock which
    is executed remotely. If you don't do this then the $vm will be $null in the remote session. If you use $using:vm then Invoke-Command will evaluate the local $vm variable and use this value in the remote session.
    $localAdminBlock = `
    $objUser = [ADSI]("WinNT://domain/domainaccount")
    $objGroup = [ADSI]("WinNT://$using:vm/Administrators")
    $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)
    Invoke-Command -ComputerName $vm -Scriptblock $localAdminBlock -Credential $adminCreds
    --Neptune
    That was the issue, thanks a lot!

  • How to run powershell in adminsitrator mode using invoke-command

    Hi,
    I'm trying to run the below script from the remote machine I'm getting the output as below and the msnpatch.exe is not getting executed on the remote machine(testserver).
    When I run the same command on the testserver, a new powershell session is getting opened and able to run msnpatch.exe.
    So, how to invoke powershell in runas administrator mode and run msnpatch.exe on that administrator window is my question.
    Thanks for your time. Your reply is highly appreciated.
    Script:
    Invoke-Command -ComputerName testserver -ScriptBlock {
    $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
    $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
    $newProcess.Verb = "runas"
    $newProcess.Arguments="-noprofile -command msnpatch.exe"
    [System.Diagnostics.Process]::Start($newProcess)
    Output:
    PS C:\Users\v-sridal> Invoke-Command -ComputerName 1f4-00073 -ScriptBlock{
    >> $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
    >> $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
    >> $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
    >> $newProcess.Verb = "runas"
    >> $newProcess.CreateNoWindow = "true"
    >> $newProcess.Arguments="-noprofile -command msnpatch.exe"
    >> [System.Diagnostics.Process]::Start($newProcess)
    >> }
    >>
    Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                   
    PSComputerName
          4       4      244       1156     8     0.06   4968 powershell                    
    testserver

    There is no elevation when running remotely. UAC only affects local sessions. You cannot elevate a remote session.
    ¯\_(ツ)_/¯

  • Suppress file deletion confirmation on remote server in Invoke-Command

    Hi!
    I try create function used for removing folders (and all content) on remote servers .
    $FullPathToDelete="\\"+("$Computername\$BasePath\$FolderToDelete").Replace("\\","\")
    if (Test-Path $FullPathToDelete -pathType container ) {
    $ScriptBlockContent = {
    paramater($FullPathToDeleteLocal)
    Get-ChildItem -Path $FullPathToDeleteLocal -Recurse | Remove-Item -Force $true -Recurse $true -Confirm:$false | Out-Null
    Invoke-Command -Computername $Computername -ScriptBlock $ScriptBlockContent -ArgumentList $FullPathToDelete -AsJob
    Remove-Item -Path $FullPathToDelete -Force | Out-Null
    Example values for variables
    $Computername = "SPPL09281"$BasePath="D$"$FolderToDelete="FolderName"
    All work but for every computer (I use this code in a loop) I receive additional prompt for confirmation
    Id Name State HasMoreData Location Command
    11 Job11 Running True SPPL09281 ...Confirm
    The item at Microsoft.PowerShell.Core\FileSystem::\\SPPL09281\D$\FolderName has children and the Recurse
    parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to
    continue?
    [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
    How I can avoid these confirmation prompts?
    Thank you in advance.
    Wojciech Sciesinski

    Hi Wojciech,
    In addition, The original confirm is reminding the folder you want to delete has subfiles, please try to add -recurse parameter:
    $FullPathToDelete="\\"+("$Computername\$BasePath\$FolderToDelete").Replace("\\","\")
    if (Test-Path $FullPathToDelete -pathType container ) {
     $ScriptBlockContent = {
      paramater($FullPathToDeleteLocal)
      Get-ChildItem -Path $FullPathToDeleteLocal -Recurse | Remove-Item -Force -Recurse -Confirm:$false | Out-Null
     Invoke-Command -Computername $Computername -ScriptBlock $ScriptBlockContent -ArgumentList $FullPathToDelete -AsJob
     Remove-Item -Path $FullPathToDelete -Recurse -Force
    If there is anything else regarding this issue, please feel free to post back.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

  • Is there a way to make invoke-command interactive?

    Hello,
    I have a script that runs an invoke-command with multiple arguments and performs operation on a remote workstation.
    I want to add some additional confirmations and dialogue choices depending on how the script block executes on the remove PC.
    Is there a way to do that?

    I'm afraid it's not possible in my scenario.
    I'm using invoke-command with Credssp authentication because I need to execute a number of commandlets that are only installed on a specific remote server. Those powershell commandlets from Microsoft do not work if installed on the client.
    Those commandlets use network share resources too, that's why Credssp is used.
    During the execution of invoke-command I wanted to make an additional confirmation for overwriting of some resources.
    The other option is to run several invoke-commands and get output from the queries, construct the dialogue options based on those queries and  gather input locally and then run the final execute invoke-command last, but it seems just like too much of
    hassle for now, so i'll leave things as they are.

  • Is it possible to pass a multi line PowerShell code block to the Invoke-Command ScriptBlock option?

    Hello,
    In my code I am trying to start a windows service on an Azure VM via Azure Automation.  My code fragment is:
    $vm = Get-AzureVM -Name $VMName -ServiceName $VMServiceName
    $uri = Get-AzureWinRMUri -ServiceName $vm.ServiceName -Name $vm.Name
    # Run a command on the Azure VM
    $PSCommandResult = InlineScript {
    $options = New-PSSessionOption -SkipCACheck
    $output = Invoke-Command -ConnectionUri $Using:uri `
    -Credential $Using:Credential `
    -SessionOption $options `
    -ScriptBlock { stop-service -DisplayName <ServiceName> -Force }
    My issue is: Is it possible to pass in a multiple line PS block as the ScriptBlock option?
    After looking around online, there appeared to be two options:
    $psblock = {
    line1
    line2
    line3
    Or
    $PSCommand = @"
    Line1
    Line2
    Line3
    But I have not been able to get either of these to work. (I was trying to end up with something like below)
    $output = Invoke-Command -ConnectionUri $Using:uri `
    -Credential $Using:Credential `
    -SessionOption $options `
    -ScriptBlock { $psCommand }
    Can someone offer a suggestion? Putting a few lines of PS code directly into the ScriptBlock parameter does work but it looks ugly!
    Thanks!

    Thanks for getting back to me!
    I have tried as you suggested but when I attempt to publish the runbook I get this error:
    Runbook definition is invalid. Cannot store the results of this type of expression into a variable. Only the results of commands, pipelines, constant expressions, foreach statements, parallel and sequence statements can be stored in variables.
     However if I just cut and paste the same code inside the ScriptBlock { CODE HERE } it works.
    Perhaps I am breaking the rule as listed above in bold? Would variable declarations in the code block not be allowed?

Maybe you are looking for