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 :-)

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

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

  • 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 to add a certificate to IIS global "Server Certificates" list using PowerShell?

    Hi, been surfing the web for an example on how to add a certificate to the "global" IIS "Server Certificates" list using PowerShell but to no luck. I already have code in place on how to tie / associate a specific website with a specific cert but not how
    to add the new .cer file using the "Complete Certificate Request..." wizard using PowerShell.... I dont expect the final code to become published but if someone had an idea on howto integrate / get an entry point on where to interact between the "Server Certificate"
    list in IIS and POSH I would be super happy! :|
    I am runnign IIS on a Windows 2008R2 x64 Standard Edition if that helps..... of course, I would saddle for an CLI if there is no other way, but POSH is of course the way to go! :)
    Thanks for the help in advance guys, take care!
    br4tt3

    Hi and thanks for the suggestions!
    Although it comes close, the suggested code example points on howto import / incorporate .pfx files - I am getting fed by .cer files which I need to add into the IIS console using POSH.
    I tried explore the IIS.CertObj object but was not able to work out if this one could be used for importing / adding .cer files into IIS! However, launching the following command from a POSH console with Import-Module Webadministration already
    loaded into that shell;
    $certMgr = New-Object -ComObject IIS.CertObj returns the following error message:
    New-Object : Cannot load COM type IIS.CertObj
    From an IIS perspective I have the following components installed;
    [X] Web Server (IIS)                                    Web-Server
        [X] Web Server                                      Web-WebServer
            [ ] Common HTTP Features                        Web-Common-Http
                [ ] Static Content                          Web-Static-Content
                [ ] Default Document                        Web-Default-Doc
                [ ] Directory Browsing                      Web-Dir-Browsing
                [ ] HTTP Errors                             Web-Http-Errors
                [ ] HTTP Redirection                        Web-Http-Redirect
                [ ] WebDAV Publishing                       Web-DAV-Publishing
            [X] Application Development                     Web-App-Dev
                [ ] ASP.NET                                
    Web-Asp-Net
                [X] .NET Extensibility                      Web-Net-Ext
                [ ] ASP                                    
    Web-ASP
                [ ] CGI                                    
    Web-CGI
                [ ] ISAPI Extensions                        Web-ISAPI-Ext
                [ ] ISAPI Filters                           Web-ISAPI-Filter
                [ ] Server Side Includes                    Web-Includes
            [ ] Health and Diagnostics                      Web-Health
                [ ] HTTP Logging                            Web-Http-Logging
                [ ] Logging Tools                           Web-Log-Libraries
                [ ] Request Monitor                         Web-Request-Monitor
                [ ] Tracing                                
    Web-Http-Tracing
                [ ] Custom Logging                          Web-Custom-Logging
                [ ] ODBC Logging                            Web-ODBC-Logging
            [X] Security                                   
    Web-Security
                [ ] Basic Authentication                    Web-Basic-Auth
                [ ] Windows Authentication                  Web-Windows-Auth
                [ ] Digest Authentication                   Web-Digest-Auth
                [ ] Client Certificate Mapping Authentic... Web-Client-Auth
                [ ] IIS Client Certificate Mapping Authe... Web-Cert-Auth
                [ ] URL Authorization                       Web-Url-Auth
                [X] Request Filtering                       Web-Filtering
                [ ] IP and Domain Restrictions              Web-IP-Security
            [ ] Performance                                 Web-Performance
                [ ] Static Content Compression              Web-Stat-Compression
                [ ] Dynamic Content Compression             Web-Dyn-Compression
        [X] Management Tools                                Web-Mgmt-Tools
            [X] IIS Management Console                      Web-Mgmt-Console
            [X] IIS Management Scripts and Tools            Web-Scripting-Tools
            [ ] Management Service                          Web-Mgmt-Service
            [ ] IIS 6 Management Compatibility              Web-Mgmt-Compat
                [ ] IIS 6 Metabase Compatibility            Web-Metabase
                [ ] IIS 6 WMI Compatibility                 Web-WMI
                [ ] IIS 6 Scripting Tools                   Web-Lgcy-Scripting
                [ ] IIS 6 Management Console                Web-Lgcy-Mgmt-Console
        [X] FTP Server                                      Web-Ftp-Server
            [X] FTP Service                                 Web-Ftp-Service
            [X] FTP Extensibility                           Web-Ftp-Ext
        [ ] IIS Hostable Web Core                           Web-WHC
    More or less the one thing that I am trying to get up and running is an automated FTPS solution - I just use the IIS console to be able to troubleshoot / compare how things scripted from POSH interacts in the MMC representation. The error I am getting
    might be that I am lacking some IIS components to be in place to be able to automate some parts of the IIS - as suggested by the IIS.CertObj object listed in the example..... I will get back if I can track down which component needs to be added to be
    able to reference the IIS.CertObj object.
    Br4tt3 signing out...
    br4tt3

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

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

  • PS Add-CMDistributionPoint "No object corresponds to the specified parameters."

    Hi,
    I'm trying to add a distribution point via Powershell. Thanks to the Add-cmdistributionpoint it should be pretty easy. The SCCM-server sccmserver1 is the main siteserver, sccmsiteserver2 is a Windows 2012 server on which all prereqs are installed and on
    which sccmsiteserver1 is member of local administrators.
    However, I get the error below "No object corresponds to the specified parameter".
    I assume the computer account of sccmsiteserver1 is used by default (couldn't trigger this error anyhow) and the parameter -sitesystemservername is not the main siteserver but the new distribution point.
    Please advise.
    J.
    PS TLS:\> Add-CMDistributionPoint -SiteSystemServerName "sccmserver2.ourdomain" -SiteCode "TLS" -ClientConnectionType Intranet -EnableAnonymous -CertificateExpirationTimeUtc "2112/12/12 12:00:00" -MinimumFreeSpace 50 -Verbose
    VERBOSE: Performing the operation "Add" on target "DistributionPoint: NewDistributionPoint".
    VERBOSE: Executing WQL query: SELECT * FROM SMS_SCI_SysResUse WHERE SiteCode='TLS'  AND RoleName='SMS Site System'  AND FileType=2  AND ItemType='System Resource Usage'  AND N
    ALPath='["Display=\\\\sccmserver2.ourdomain\\"]MSWNET:["SMS_SITE=TLS"]\\\\sccmserver2.ourdomain\\'
    VERBOSE: Query returned 0 results.
    Add-CMDistributionPoint : No object corresponds to the specified parameters.
    At line:1 char:1
    + Add-CMDistributionPoint -SiteSystemServerName "sccmserver2.ourdomain" -SiteCod ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:String) [Add-CMDistributionPoint], ItemNotFoundException
        + FullyQualifiedErrorId : SessionStateException,Microsoft.ConfigurationManagement.Cmdlets.HS.Commands.AddDistributionPointCommand
    Jan Hoedt

    Yes, just a typo, sorry.
    What worries me is that the output of the query is 0 "VERBOSE: Query returned 0 results."
    So that means everything is working but there is actually no result to the query. Not sure why though. 
    Jan Hoedt

  • 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

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

  • Are there any memory restrictions when using Invoke-Command?

    Hi, I'm using the Invoke-PSCommandSample workbook to run a batch file inside a VM.
    The batch file inside the VM runs a Java program.
    The batch file works fine, when I run it manually in the VM.
    However, when I use the Invoke-PSCommandSample workbook to run the batch file, I get the following error:
    Error occurred during initialization of VM
    Could not reserve enough space for object heap
    errorlevel=1
    Press any key to continue . . .
    Does anybody know if there are any memory restrictions when invoking commands inside a VM via runbook?
    Thanks in advance.

    Hi Joe, I'll give some more background information. I'm doing load testing with JMeter in Azure and I want to automate the task. This is my runbook:
    workflow Invoke-JMeter {
    $Cmd = "& 'C:\Program Files (x86)\apache-jmeter-2.11\bin\jmeter-runbook.bat'"
    $Cred = Get-AutomationPSCredential -Name "[email protected]"
    Invoke-PSCommandSample -AzureSubscriptionName "mysubscription" -ServiceName "myservice" -VMName "mymachine" -VMCredentialName "myuser" -PSCommand $Cmd -AzureOrgIdCredential $Cred
    This is my batch file inside the VM:
    set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_71
    set PATH=%JAVA_HOME%\bin;%PATH%
    %COMSPEC% /c "%~dp0jmeter.bat" -n -t build-web-test-plan.jmx -l build-web-test-plan.jtl -j build-web-test-plan.log
    Initially I tried to run JMeter with "-Xms2048m -Xmx2048m". As that didn't work, I lowered the memory allocation but even with "-Xms128m -Xmx128m" it does not work. I have tried with local PowerShell ISE as you suggested, but I'm
    running into certification issues. I'm currently have a look at this. Here's my local script:
    Add-AzureAccount
    Select-AzureSubscription -SubscriptionName "mysubscription"
    $Uri = Get-AzureWinRMUri -ServiceName "myservice" -Name "mymachine"
    $Credential = Get-Credential
    $Cmd = "& 'C:\Program Files (x86)\apache-jmeter-2.11\bin\jmeter-runbook.bat'"
    Invoke-command -ConnectionUri $Uri -credential $Credential -ScriptBlock {
    Invoke-Expression $Args[0]
    } -Args $Cmd
    With this, I get the following error (sorry, it is in German):
    [myservice.cloudapp.net] Beim Verbinden mit dem Remoteserver "myservice.cloudapp.net" ist folgender Fehler
    aufgetreten: Das Serverzertifikat auf dem Zielcomputer (myservice.cloudapp.net:666) enthält die folgenden
    Fehler:
    Das SSL-Zertifikat ist von einer unbekannten Zertifizierungsstelle signiert. Weitere Informationen finden Sie im
    Hilfethema "about_Remote_Troubleshooting".
        + CategoryInfo          : OpenError: (myservice.cloudapp.net:String) [], PSRemotingTransportException
        + FullyQualifiedErrorId : 12175,PSSessionStateBroken

  • How to add a certificate to keystore using keytool?

    Hi all,
    I am trying to connect a server from my application which requires a certificate for secure connection.
    I am using Jdeveloper. Should I use command prompt and use keytool command after going to jdk home of jdeveloper and add the certificate?
    What password should I use?
    Sam

    Consult for example:
    http://www.thatsjava.com/java-tech/38248/
    http://www.oracle.com/technology/sample_code/tech/java/codesnippet/ejb/applettoejb/HowTo_Applet_talks_to_Session_bean.html
    http://oraforms.blogspot.com/2009/02/setting-up-jdeveloper-for-httpsssl.html
    NA
    http://nickaiva.blogspot.com

  • 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

Maybe you are looking for

  • TS1702 On the game "pinball HD" for the Ipad the right flipper does not work on my 2 ipads

    I have two ipads one is the original that first came out and the other is an Ipad mini.  I have installed on both the piball game "pinball HD".   On both devices the right flipper on the game does not work.  Seems strange it is happening on both my d

  • Plug off the ethernet cable, ox y yosemite crashes, laptop shuts down

    Hi, I Just had recently another  problem : I use the etherent cable for faster internet speed, but if I unplug it, or it comes off, my entire computer shuts down. Is PRAM the answer, I seemed to read that everywhere with Yosemite bugs, thanks for any

  • Issue in vl10b transaction in SHP_VL10_DELIVERY_CREATE

    Hi friends,                 I am facing a problem in vl10b transaction. when i execute this transaction for return good receipt, it gives me an error saying No data exists for delivery 80000292. I debuged it and found that it is returning this error

  • IP Multicast requirements in WebLogic 5.1 cluster

              Hi,           Does multicast need to be available to servers containing the Weblogic plug-in?           We have a firewall between web servers (iPlanet) and the WebLogic cluster.           Thanks in advance,           Julian           

  • PCI Device and Network Controller uninstalle​d

    Having problems with downloading a pci device and network controller driver for presario cq57? Need help. my hardware id is PCI\VEN_10EC&DEV_5209&SUBSYS_3577103C&REV_01