Invoke-command -computername RemoteServer {start-process c:\install\.bat}

I am running an invoke command from a PC to run a .bat file on a remote server. However i would like to see the output of the .bat file run in my powershell window on my local PC. Any tips on this?
I have this at the moment
invoke-command -computername Server {start-process c:\install\.bat}
however this just completes without showing  me anything. Can i see the output of the .bat file on my local PC?
Thanks in advance

invoke-command -computername Server01 -filepath c:\Scripts\scriptname.ps1
The script has to be on the local machine or has access to it.
If this is helpful please mark it so. Also if this solved your problem mark as answer.

Similar Messages

  • 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

  • Invoke-WMIMethod failed to start process on remote server

    Hi Folks,
    I am trying to run an exe in remote server to automate some of my application startup process in disconnected mode(Using powershell 2.0). However Invoke-WmiMethod does not trigger the application but start-process triggers it fine. I am trying following
    command -
    $FullExecutable = "\\remoteserver\abc\project\environment\ServerApplications\ApplicationDirectory\App.exe"
    $Arguments = "stanza=ApplicationVariable"
    PS Microsoft.PowerShell.Core\FileSystem::\\remoteserver\abc\project\environment\ServerApplications\ApplicationDirectory> Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "$FullExecutable $Arguments"
    I tried these options but no luck -
    http://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx
    Please help me fixing this issue. Thanks for any advice.
    Charlie

    Hi Charlie,
    Since I have no test app.exe file, I tested with notepad.exe and ran these scripts to open local file D:\1.txt, would you please list the test results with app.exe:
    $a="Notepad.exe"
    $b="D:\1.txt"
    Invoke-WMIMethod -Class Win32_Process -Name Create -ArgumentList "$a $b"
    ([wmiclass]"win32_Process").create("$a $b")
    Start-Process $a -ArgumentList $b -wait -NoNewWindow -PassThru
    If you have any other questions, please feel free to let me know.
    Best Regards,
    Anna Wang

  • Installing SQL Server 2012 remotely via Powershell using Invoke-Command

    I am trying to perform a SQL Server 2012 command line installation using Powershell Invoke-Command on Windows 2012 Datacenter.
    The code I am using is as follows:
     $ret = Invoke-Command -ComputerName $COMPUTER -ArgumentList $MEDIA,$ACTION,$FEATURES,$INSTALLDIR,$INSTANCEID,$INSTANCENAME,$SQLDATADRIVE,$SQLLOGDRIVE,$DOMAIN,$SQLSERVERSERVICEUSER,$SQLSERVICEPASSWORD,$PRODUCTKEY,$SQLSERVERSA,$username,$ADMINPASSWD
    -Credential $cred -ScriptBlock {
      param($MEDIA,
         $ACTION,
         $FEATURES,
         $INSTALLDIR,
         $INSTANCEID,
         $INSTANCENAME,
         $SQLDATADRIVE,
         $SQLLOGDRIVE,
         $DOMAIN,
         $SQLSERVERSERVICEUSER,
         $SQLSERVICEPASSWORD,
         $PRODUCTKEY,
         $SQLSERVERSA,
         $USERNAME,
         $PASSWD)
      Set-Location $MEDIA
      Import-Module ServerManager
      if (-not [IO.Directory]::Exists($MEDIA)){
       $hn = hostname
       return 0,"Failed to find SQL Server Installer at $MEDIA on $hn"
      $tran = ""
      Try{
       & $MEDIA\setup.exe /ACTION=$ACTION /Q /FEATURES=$FEATURES /IACCEPTSQLSERVERLICENSETERMS /UPDATEENABLED=False /INSTALLSHAREDDIR="$INSTALLDIR\Program Files\Microsoft SQL Server" /INSTALLSHAREDWOWDIR="$INSTALLDIR\Program Files
    (x86)\Microsoft SQL Server" /RSINSTALLMODE="FilesOnlyMode" /INSTANCEID="$INSTANCEID" /INSTANCENAME="$INSTANCENAME" /INSTANCEDIR="$INSTALLDIR\Program Files\Microsoft SQL Server" /ENU="True" /AGTSVCSTARTUPTYPE="Automatic"
    /SQLSVCSTARTUPTYPE="Automatic" /NPENABLED=1 /TCPENABLED=1 /RSSVCStartupType="Automatic" /ERRORREPORTING=0 /SQMREPORTING=0 /INDICATEPROGRESS /INSTALLSQLDATADIR="$SQLDATADRIVE\DATA" /SQLUSERDBDIR="$SQLDATADRIVE\DATA" /SQLUSERDBLOGDIR="$SQLLOGDRIVE\LOG"
    /ASDATADIR="$SQLDATADRIVE\OLAP\DATA" /ASLOGDIR="$SQLLOGDRIVE\OLAP\Log" \ASBACKUPDIR="$SQLDATADRIVE\OLAP\Backup" \ASTEMPDIR="$SQLDATADRIVE\OLAP\Temp" /ASCONFIGDIR="$SQLDATADRIVE\OLAP\Config" /ASCOLLATION="Latin1_General_CI_AS"
    /SQLCOLLATION="SQL_Latin1_General_CP1_CS_AS" /SQLSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /SQLSVCPASSWORD="$SQLSERVICEPASSWORD" /AGTSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /AGTSVCPASSWORD="$SQLSERVICEPASSWORD"
    /ASSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /ASSVCPASSWORD="$SQLSERVICEPASSWORD" /RSSVCACCOUNT="$DOMAIN\$SQLSERVERSERVICEUSER" /RSSVCPASSWORD="$SQLSERVICEPASSWORD" /FTSVCACCOUNT="NT AUTHORITY\LOCAL SERVICE"
    /INDICATEPROGRESS > $out
      } Catch [System.Exception] {
       return 0,$_.Exception.ToString()
      if ($tran -ne ""){
       $out += $tran
      return 1,$out
    The media resides on the server that I am remoting to in powershell and the server is on the same domain. The credentials I pass are for a Domain Admin, but SQL Server fails to validate the credentials for the passed parameter for the sql service user with
    a Access Denied.
    If I run the same command with the same user directly on the server it works fine.
    My guess is that the elavated privs for Administrator are not being set when using Invoke-Command? Is there a way to utilize powershell to install SQL Server 2012 with command line option using the invoke-command and passing credentials? Or is this a limitation
    to the SQL Server installer. If there is can a example be provided?

    Ok, so with the help of some friends, we found a fix that works!
    Prior to running the Invoke-Command I now run:
    # enable CredSSP on a client computer; this command allows the client credentials to be delegated to the server01 computer.:
    Enable-WsManCredSSP -Role Client -DelefateComputer server.some.domain.com
    Then I add the -Authentication option to my Invoke-Command with option Credssp.
    The install the works fine. Hope this helpes all.

  • 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 Hodges

    I 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

  • 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.
    ¯\_(ツ)_/¯

  • Invoke-Command & Add-CMDistributionPoint - Certificate failure

    Hi together,
    for automatic creation of Distribution Points I am doing the following things.
    Doing this locally on the Primary Site Server as Network Access Account everything works fine.
    But when I try to do this with invoke-command on my machine with Network Access Account too, I'll get an error:
    WARNING: The self signed certificate could not be created successfully.
    What am I doing wrong?
    Here is what I am doing locally:
    Write-Host "------------------NOW Running on REMOTE Primary Site----------------" -BackgroundColor Yellow -ForegroundColor Black
    if(!(Test-Path $RemoteSCCMModule))
    Write-Error "Could not find Remote SCCM Module!"
    Exit
    Write-Debug "Importing SCCM Module..."
    Import-Module $RemoteSCCMModule -Force
    $SiteLocation = $SiteCode + ":"
    Set-Location $SiteLocation | Out-Null
    if(($BoundaryName -ne "") -and ($BoundaryName -ne " ") -and ($BoundaryName -ne $null) -and ($BoundaryName -ne $false))
    $BoundaryValue = $BoundaryStartIP + "-" + $BoundaryEndIP
    New-CMBoundary -DisplayName $BoundaryName -BoundaryType IPRange -Value $BoundaryValue
    New-CMBoundaryGroup -Name $BoundaryGroupName
    Add-CMBoundaryToGroup -BoundaryGroupName $BoundaryGroupName -BoundaryName $BoundaryName
    New-CMSiteSystemServer -ServerName $using:NewDPServer -SiteCode $using:SiteCode
    Start-Sleep -Seconds 2
    Add-CMDistributionPoint -SiteSystemServerName $NewDPServer -SiteCode $SiteCode -MinimumFreeSpaceMB $MinimumFreeDiskSpace -EnablePxeSupport -AllowRespondIncomingPxeRequest -EnableUnknownComputerSupport -ComputersUsePxePassword $PXEPassword -UserDeviceAffinity DoNotUse -PxeServerResponseDelaySeconds 5 -CertificateExpirationTimeUtc $CertExpirationDate
    Start-Sleep -Seconds 2
    Foreach($DPGroup in $NewDPServer_Groups)
    Add-CMDistributionPointToGroup -DistributionPointGroupName $DPGroup -DistributionPointName $NewDPServer
    And this is what I am doing with Invoke-Command:
    Invoke-Command -ComputerName $PrimarySiteServer -ConfigurationName Microsoft.PowerShell32 -Credential $NAACred -ScriptBlock {
    $DebugPreference = $using:DebugPreference
    Write-Host "------------------NOW Running on REMOTE Primary Site----------------" -BackgroundColor Yellow -ForegroundColor Black
    Write-Debug "Importing SCCM Module..."
    Import-Module $using:RemoteSCCMModule -Force
    $SiteLocation = $using:SiteCode + ":"
    Set-Location $SiteLocation | Out-Null
    if(($using:BoundaryName -ne "") -and ($using:BoundaryName -ne " ") -and ($using:BoundaryName -ne $null) -and ($using:BoundaryName -ne $false))
    $BoundaryValue = $using:BoundaryStartIP + "-" + $using:BoundaryEndIP
    New-CMBoundary -DisplayName $using:BoundaryName -BoundaryType IPRange -Value $BoundaryValue
    New-CMBoundaryGroup -Name $using:BoundaryGroupName
    Add-CMBoundaryToGroup -BoundaryGroupName $using:BoundaryGroupName -BoundaryName $using:BoundaryName
    New-CMSiteSystemServer -ServerName $using:NewDPServer -SiteCode $using:SiteCode
    Start-Sleep -Seconds 2
    Add-CMDistributionPoint -SiteSystemServerName $using:NewDPServer -SiteCode $using:SiteCode -MinimumFreeSpaceMB $using:MinimumFreeDiskSpace -EnablePxeSupport -AllowRespondIncomingPxeRequest -EnableUnknownComputerSupport -ComputersUsePxePassword $using:PXEPassword -UserDeviceAffinity DoNotUse -PxeServerResponseDelaySeconds 5 -CertificateExpirationTimeUtc $using:CertExpirationDate
    Start-Sleep -Seconds 2
    Foreach($DPGroup in $using:NewDPServer_Groups)
    Add-CMDistributionPointToGroup -DistributionPointGroupName $DPGroup -DistributionPointName $using:NewDPServer
    If you need more information what different valus of variables are i can provide.
    Thank you.
    Kind regards
    Martin Krämer

    Hi,
    Here is the whole script - I'm still testing around this is why it is not really nice at the moment ;-) :
    $DebugPreference = "Continue"
    $Script:Script= $MyInvocation.MyCommand.Definition
    $Script:DebugOut = "Script started: " + "$Script:Script"
    Write-Debug $Script:DebugOut
    $Script:ScriptPath = Split-Path -Path $Script:Script -Parent
    $CertExpirationDate = (Get-Date).AddYears(100)
    #region Setting_Variables
    $NAACred = Get-Credential -Message "provide NetworkAccessAccount credentials:" -UserName "test.loc\NAA_User"
    [string]$RemoteSCCMModule = "D:\ConfigMgr\AdminConsole\bin\ConfigurationManager.psd1"
    [string]$PrimarySiteServer = "Test-Primary"
    [string]$SiteCode = "KN1"
    [string]$NewDPServer = "TEST-DP.test.loc"
    $PXEPassword = ConvertTo-SecureString -AsPlainText "mypass" -Force
    [int]$MinimumFreeDiskSpace = 2000
    [string]$BoundaryName = " "
    [string]$BoundaryStartIP = "192.168.30.1"
    [string]$BoundaryEndIP = "192.168.30.254"
    [string]$BoundaryGroupName = "TEST-DP_Group"
    [array]$NewDPServer_Groups = "04 All Aviable DPs", "01 All PXE DPs"
    #endregion Setting_Variables
    #region REMOTE PrimarySiteServerScript
    <#
    IF ($env:PROCESSOR_ARCHITECTURE -ne "x86")
    Write-Debug "Powershell needs to be in x86 mode. Restarting powershell..."
    $PS32exe = "$env:windir\SysWOW64\WindowsPowerShell\v1.0\powershell.exe"
    if(!(Test-Path $PS32exe))
    Write-Error "x86 Powershell not found!"
    exit
    $powershell = [System.Diagnostics.Process]::GetCurrentProcess()
    $psi = New-Object System.Diagnostics.ProcessStartInfo $powerShell.Path
    $script = $MyInvocation.MyCommand.Path
    $prm = $script
    foreach($a in $args)
    $prm += ' ' + $a
    $psi.Arguments = $prm
    $psi.FileName = $PS32exe
    [System.Diagnostics.Process]::Start($psi) | Out-Null
    exit
    Else
    Write-Debug "Powershell already in x86 mode..."
    if(!(Test-Path $using:RemoteSCCMModule))
    Write-Error "Could not find Remote SCCM Module!"
    Exit
    #>
    <#
    Invoke-Command -ComputerName $PrimarySiteServer -ConfigurationName Microsoft.PowerShell32 -Credential $NAACred -ScriptBlock {
    $DebugPreference = $using:DebugPreference
    Write-Host "------------------NOW Running on REMOTE Primary Site----------------" -BackgroundColor Yellow -ForegroundColor Black
    Write-Debug "Importing SCCM Module..."
    Import-Module $using:RemoteSCCMModule -Force
    $SiteLocation = $using:SiteCode + ":"
    Set-Location $SiteLocation | Out-Null
    if(($using:BoundaryName -ne "") -and ($using:BoundaryName -ne " ") -and ($using:BoundaryName -ne $null) -and ($using:BoundaryName -ne $false))
    $BoundaryValue = $using:BoundaryStartIP + "-" + $using:BoundaryEndIP
    New-CMBoundary -DisplayName $using:BoundaryName -BoundaryType IPRange -Value $BoundaryValue
    New-CMBoundaryGroup -Name $using:BoundaryGroupName
    Add-CMBoundaryToGroup -BoundaryGroupName $using:BoundaryGroupName -BoundaryName $using:BoundaryName
    New-CMSiteSystemServer -ServerName $using:NewDPServer -SiteCode $using:SiteCode
    Start-Sleep -Seconds 2
    Add-CMDistributionPoint -SiteSystemServerName $using:NewDPServer -SiteCode $using:SiteCode -MinimumFreeSpaceMB $using:MinimumFreeDiskSpace -EnablePxeSupport -AllowRespondIncomingPxeRequest -EnableUnknownComputerSupport -ComputersUsePxePassword $using:PXEPassword -UserDeviceAffinity DoNotUse -PxeServerResponseDelaySeconds 5 -CertificateExpirationTimeUtc $using:CertExpirationDate
    Start-Sleep -Seconds 2
    Foreach($DPGroup in $using:NewDPServer_Groups)
    Add-CMDistributionPointToGroup -DistributionPointGroupName $DPGroup -DistributionPointName $using:NewDPServer
    #>
    #endregion REMOTE PrimarySiteServerScript
    #region LOCAL PrimarySiteServerScript
    Write-Host "------------------NOW Running on REMOTE Primary Site----------------" -BackgroundColor Yellow -ForegroundColor Black
    if(!(Test-Path $RemoteSCCMModule))
    Write-Error "Could not find Remote SCCM Module!"
    Exit
    Write-Debug "Importing SCCM Module..."
    Import-Module $RemoteSCCMModule -Force
    $SiteLocation = $SiteCode + ":"
    Set-Location $SiteLocation | Out-Null
    if(($BoundaryName -ne "") -and ($BoundaryName -ne " ") -and ($BoundaryName -ne $null) -and ($BoundaryName -ne $false))
    $BoundaryValue = $BoundaryStartIP + "-" + $BoundaryEndIP
    New-CMBoundary -DisplayName $BoundaryName -BoundaryType IPRange -Value $BoundaryValue
    New-CMBoundaryGroup -Name $BoundaryGroupName
    Add-CMBoundaryToGroup -BoundaryGroupName $BoundaryGroupName -BoundaryName $BoundaryName
    New-CMSiteSystemServer -ServerName $using:NewDPServer -SiteCode $using:SiteCode
    Start-Sleep -Seconds 2
    Add-CMDistributionPoint -SiteSystemServerName $NewDPServer -SiteCode $SiteCode -MinimumFreeSpaceMB $MinimumFreeDiskSpace -EnablePxeSupport -AllowRespondIncomingPxeRequest -EnableUnknownComputerSupport -ComputersUsePxePassword $PXEPassword -UserDeviceAffinity DoNotUse -PxeServerResponseDelaySeconds 5 -CertificateExpirationTimeUtc $CertExpirationDate
    Start-Sleep -Seconds 2
    Foreach($DPGroup in $NewDPServer_Groups)
    Add-CMDistributionPointToGroup -DistributionPointGroupName $DPGroup -DistributionPointName $NewDPServer
    #endregion LOCAL PrimarySiteServerScript
    Thank you for help :-)

  • 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!

  • 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

  • Using invoke-command to run 'vssadmin list writers' on several servers, how do I sort the results from each server?

    Hi I am a PS virgin so be gentle with me. I am trying to run the vssadmin list writers command on 8 servers.
    invoke-command -computername srv-bx-hvc1, srv-bx-hvc2, srv-bx-hvc3, srv-bx-hvc4,
    srv-bx-hvc5,
    srv-bx-hvc6,
    srv-bx-hvc7, srv-bx-hvc8
    -command {vssadmin list writers}
    The command works but I cannot tell which response is from what server.
    The objective whould be to eventually have the command so I know which server has  failed vss writers if possible restart them automatically.
    Any thoughts on how to achieve this lofty ideal??
    Thanks

    This is a tweak to the example that JRV listed.  I am using this code to just pull the information about the Exchange Writers but you could adapt it for others.
    $servers='sdcexmail001','sdcexmail002','sdcexmail003','sdcexmail004','sdcexmail005'
    $servers | %{
    $sb={
    $writers=vssadmin list writers
    New-Object PSObject -Property @{Server=$_;Writers=$writers}
    $ServerName = $_
    $out = invoke-command -computername $_ -scriptblock $sb -Argumentlist $_
    $WritersData = $Out.Writers
    for ($I = 0;$I -le $WritersData.Count -1;$I++)
    $Data = $WritersData[$I]
    If($Data.StartsWith('Writer name:'))
    $WriterName = ($Data.Split(':')[1]).Trim()
    $WriterID = ($WritersData[$I+1].Split(':')[1]).Trim()
    $WriterInstID = ($WritersData[$I+2].Split(':')[1]).Trim()
    $State = ($WritersData[$I+3].Split(':')[1]).Trim()
    $LastError = ($WritersData[$I+4].Split(':')[1]).Trim()
    $info = [Ordered]@{
    'ComputerName' = "$ServerName";
    'WriterName' = "$WriterName";
    'WriterID' = "$WriterID";
    'WriterInstID' = "$WriterInstID";
    'State' = "$State";
    'LastError' = "$LastError";
    $object = New-Object -TypeName psobject -Property $info
    $object | Where-Object {$_.WriterName -like '*Microsoft Exchange*'} | Select-Object -Property ComputerName,WriterName,State,LastError

  • Logging Invoke-Command

    Hello,
    I have a problem with logging on multiple servers at the same time. I would like to have a single file with every log formated like this :
    "yyyyMMdd HH:mm:ss - $Env:ComputerName - result of the command"
    To know what computer is doing what, I am currently logging in separate files on each server running the following code :
    $ExecDate = Get-Date -Format yyyy-MM-dd_HH-mm
    $TroncateLocalLogFileName = "C:\Temp\$ExecDate"
    $ScriptBlock= {
    Param ($TroncateLocalLOgFileName)
    Get-Date
    Echo *****************
    Write-Host "Blablabla is running on" $Env:ComputerName ", please wait..."
    Echo "Blablabla is running, please wait..."
    & "C:\Program Files\firstscript.ps1"
    Echo *****************
    Echo "Enabling BLABLABLA for $env:computername..."
    Set-ItemProperty -Path HKLM:\MyRegistryPath -name MyRegistryKey -Value 1
    Echo *****************
    Echo "End of procedure"
    Write-Host "BALBALBLA for" $env:computername "is done"
    Echo *****************
    Get-Date
    } > $TroncateLocalLOgFileName"_$Env:ComputerName.log" 2>&1
    invoke-command -ComputerName $ListOfServers -ArgumentList $TroncateLocalLogFileName -ScriptBlock $ScriptBlockforeach ($Computer in $ListOfServers) {
    robocopy \\$Computer\$LogSource $LogDestination\ $Execdate"_*" /MOV
    Does anyone knows how to add some string to output inside an Invoke-Command to get the required result ?
    I tried everything I could think of without anything getting near...
    Thanks in advance for your help.

    Hi Pierre,
    If you want to export the result to a single log file instead of mutiple log files located on every remote computers, please try to export the log file outside the scriptblock of the the cmdlet "Invoke-Command", and use the cmdlet "Out-File"
    to append every result from remote computers to a single file:
    $ExecDate = Get-Date -Format yyyy-MM-dd_HH-mm
    $TroncateLocalLogFileName = "C:\Temp\$ExecDate"
    $ScriptBlock= {
    Param ($TroncateLocalLOgFileName)
    Get-Date
    Echo *****************
    Write-Host "Blablabla is running on" $Env:ComputerName ", please wait..."
    Echo "Blablabla is running, please wait..."
    & "C:\Program Files\firstscript.ps1"
    Echo *****************
    Echo "Enabling BLABLABLA for $env:computername..."
    Set-ItemProperty -Path HKLM:\MyRegistryPath -name MyRegistryKey -Value 1
    Echo *****************
    Echo "End of procedure"
    Write-Host "BALBALBLA for" $env:computername "is done"
    Echo *****************
    Get-Date
    invoke-command -ComputerName $ListOfServers -ArgumentList $TroncateLocalLogFileName -ScriptBlock $ScriptBlock | out-file $TroncateLocalLOgFileName"_$Env:ComputerName.log" -append
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang

  • 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 Set-Item wsman : Access Denied

    Hi,
    I'm trying to write a script that run another script via an Invoke-Command cmdlet. This script is :
    $usrname = "[email protected]"
    $pwd = "MonPassword"
    $pwd = ConvertTo-SecureString -AsPlainText $pwd -Force
    $cred1 = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $usrname, $pwd
    Invoke-Command -ComputerName "SRVFWL" -FilePath "c:\Scripts\VPNScript.ps1" -Credential $cred1
    So this first script run the next script with the user [email protected] :
    $ID = "UserID"
    $RCMPUSR = "UsrOnVpnCmp"
    $RCMPPWD = "MyPass"
    $RCMPPWD = ConvertTo-SecureString -AsPlainText $RCMPPWD -Force
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $RCMPUSR, $RCMPPWD
    #Connection to RRAS TMG 2010
    $root = New-Object -ComObject "FPC.Root"
    $isaarray = $root.GetContainingArray()
    $sessionmonitor = $isaarray.SessionsMonitors.SessionsMonitorFirewall
    $filter = New-object -ComObject FPC.FPCFilterExpressions
    #Retreive VPN session
    $sessionmonitor.ExecuteQuery($filter,10000)
    #Check session
    foreach($session in $sessionmonitor)
    if($session.ClientIP.StartsWith("10.10."))
    if($session.ClientUserName -eq "MYDOM\\"+$ID)
    Set-Item wsman:\localhost\client\trustedhosts $session.ClientIP -Force
    If((Test-WSMan $session.ClientIP).IsEmpty -eq $false)
    $CMPName = Invoke-Command -ComputerName $session.ClientIP -ScriptBlock {$(Get-WmiObject Win32_Computersystem).name} -credential $cred
    $Version = Invoke-Command -ComputerName $session.ClientIP -ScriptBlock {[Environment]::OSVersion.Version} -credential $cred
    If($Version.Major -eq 6)
    $sessionmonitor.DisconnectSession("MyTMGServer",$session.SessionID)
    $usr = $ID + "@mydom.pri"
    netsh ras set client $usr disconnect
    return $true
    $sessionmonitor.EndQuery()
    This second script run greatly when I run it manually on the local server connected with the svc_scripts user. But I've a Access Denied on the Set-Item cmdlet of the second script when i try to run it with the Invoke-Command.
    I don't understand why this same user are allowed to run the script locally but not allowed on remote computer.
    Can you help me ?
    Thank you.

    Hi Judicael44,
    First You will encounter the second-hop issue when run "invoke-commmand" as the scriptblock in another remote cmdlet, for more detailed information, please refer to this article:
    Enabling Multihop Remoting
    For the error you posted, Let me restate this issue, we have two servers:
    Local server: server1
    remote server: SRVFWL
    So the second script is located on server1, and the user "[email protected]" has admin right on server
    SRVFWL, you got the error "access denied" when ran the script on remote server SRVFWL.
    In this case, please make sure you have ran the cmdlet "Enable-PSRemoting -Force" on server SRVFWL, which will give you the rights to access and modify TrustedHosts setting in WinRm.
    I tested with single cmdlet, and this could work:
    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

Maybe you are looking for