Running a command in a remote Powershell session

Hi,
I have used the Enter-PSSession to get a remote session on a domain controller... all is ok with that.
when i run the following command it fails, however if i run this locally on the domain controller it succeeds. this command is correct, it just fails with the remote powershell session
dsacls.exe "OU=MYTestOU,OU=Servers,DC=MyDomain,DC=Local" /G "mydomain\MyComputer$":GRGWCC
I have tried placing c:\windows\system32 before the exe, and i have also tried cmd /c dsacls.exe .........
i cant figure out why this doesnt work, can anyone help?
thanks
Steve

strange, if i run the command for a user account instead of a computer account and remove the "" around it, it works.
dsacls.exe "OU=MYTestOU,OU=Servers,DC=MyDomain,DC=Local" /G mydomain\steve:GRGWCC
it must be that $ sign that is causing the problems....?

Similar Messages

  • Inconsistent behavior of "where" filter command in remote powershell session

    I've got a simple powershell script I've written to do a gpo backup (backup-gpo) to a remote file share, and then I launch a remote powershell session with "invoke-command" where I zip up the results of the gpo backup, then delete the gpo
    backups once the files are safely zipped.
    What I'm seeing, and I've never seen before, is very inconsistent results in the file filtering statements.  I use the following line twice in my code to find the files written by the GPO backup:
     Get-ChildItem -Force | ? {($_.lastwritetime.date -eq (Get-Date).date) -and ($_.name -notlike "*.zip")}
    The first time it finds the files to zip, the second time it finds the files to delete.  It's a copy/paste, so it's the exact same code.
    The weirdness that happens is some nights, it works fine, and both filters match what they should.  The GPO backup results are found, zipped, and then deleted.  Other nights, the first filter will match all old *.zip files (the exact
    opposite of the filter), and zip them up - then the "delete" filter, which is the exact same code, will match correctly and delete the GPO backup results that should have been zipped but weren't.
    Last night the first filter matched correctly, and then the second filter matched the date portion of the filter, ignored the *.zip portion, and deleted everything in the target folder from that day. 
    Anyone seen anything like this?

    Hi Nbhms,
    Any updates about this issue?
    If you need further help, please feel free to reply this post directly
    so we will be notified to follow it up.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna
    TechNet Community Support

  • [Exchange 2013/Online][PS] How to retrieve existing remote PowerShell sessions

    I'm trying to figure out how to retrieve all existing remote PowerShell sessions (user-managed) between a client and an Exchange 2013 server.
    Running Get-PSSession only returns remote sessions created within the current PowerShell session (system-managed). I need to do this from within a
    different PowerShell session, possibly even from a different computer from where those remote sessions were established.
    Documentation for Get-PSSession states that this should be possible starting with PS 3.0 since user-managed sessions are now stored locally on the remote server (in my case, the Exchange 2013 server) and can later be retrieved from any system-managed session
    by using Get-PSSession with either the ComputerName or ConnectionUri parameter sets.
    Here's how those remote sessions are created:
    PS $> $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://<exchange_server>/powershell/ -Credential $credential -Authentication Basic -AllowRedirection
    PS $> Import-PSSession $Session
    And how I try to retrieve those session afterward:
    PS $> Get-PSSession -ComputerName <exchange_server> -ApplicationName powershell -Authentication Basic -Credential $credential -UseSSL -Port 443
    PS $> Get-PSSession -ConnectionUri https://<exchange_server>/powershell/ -AllowRedirection -Authentication Basic -Credential $credential
    Both methods yield no results (nor errors), while running Get-PSSession (without any parameters) within the same user-managed session would successfully return the session. 
    The only explanation I could think of right now is that somehow, WinRM on the Exchange server is not running PS 3.0 even though:
    $PSVersionTable.PSVersion returns 3 0 -1 -1
    winrm id returns ProductVersion = OS: 6.2.9200 SP: 0.0
    Stack: 3.0
    But when I attempt to disconnect a remote session with this Exchange server using Disconnect-PSSession, I get the
    following error message: 
    Disconnect-PSSession : Disconnect-PSSession operation failed for runspace Id = XXXXX
    for the following reason: The disconnection operation is not supported on the remote computer. To support
    disconnecting, the remote computer must be running Windows PowerShell 3.0 or a later version of Windows PowerShell.
    So I guess I have a couple questions:
    Are remote PSSession even supposed to be maintained on
    an Exchange 2013 server? 
    If so, is it possible to retrieve them from a different session using GET-PSSession?
    Which version of PS 3.0 is used by WinRM on an Exchange 2013 server?
    thanks

    Thanks for your help. 
    1. I know that remote PS sessions are supported, I have no issue connecting to the Exchange server. The issue is with
    reconnecting to an existing PS session.
    2. As mentioned in my original post, PS & WinRM 3.0 are installed on the client:
    $PSVersionTable.PSVersion returns 3
    0 -1 -1
    winrm
    id returns ProductVersion = OS: 6.2.9200 SP: 0.0 Stack:
    3.0

  • Constrained Delegation For Remote Powershell Sessions

    Consider the case of a client (let's call it Client) doing a remote Powershell session to a server (ServerA). In this Active Directory environment, the client has full administrative permissions over ServerA. To create the
    session, the client opens a Powershell console and types:
    $ps = New-PSSession -ComputerName ServerA
    Enter-PSSession $ps
    From this point, the client wants to be able to open a different remote Powershell session to another server (ServerB). Again, he's having administrative permissions over this server as well. If he goes ahead and uses the cmdlet below:
    $newPS = New-PSSession -ComputerName ServerB
    ...this won't work by default due to the
    Kerberos double hop issue.
    A way to make this work is enable delegation for the Client AD account (by adding a dummy SPN and also making sure the
    Account is sensitive and cannot be delegated isn't enabled), and turn on unconstrained delegation for the
    ServerA computer account in Active Directory. After this is done, as soon as the 1st remote PS session is entered, issuing a 'klist' will reveal a Kerberos TGT for Client, with the 'forwarded' flag set. The 2nd remote PS session can be made without
    any issues now to ServerB.
    However, in order to make this more secure, as to not have ServerA being able to act on behalf of Client to any target machine, but only against
    ServerB, constrained delegation can be used. So the ServerA's Delegation tab in AD is changed as to contain only the
    http/ServerB.fqdn (since we're using Powershell remoting). The problem is that trying to initiate the 2nd connection fails just as in the original case (logon session does not exist). Checking things further, I've noticed that after the 1st session
    is entered, issuing a 'klist' only reveals an http/ServerB.fqdn Kerberos ticket, and no longer any Kerberos TGTs. However reading the documentation surrounding constrained delegation (namely the S4U2Proxy component)
    here, it doesn't look as the TGT should be present there.
    The question is why cannot constrained delegation be used here or more likely, what is it I'm doing wrong ?
    Note that CredSSP is a mechanism that I wouldn't want to use here. Also, even though this entry contains a lot of Active Directory information, I thought it would be relevant for the Powershell community to post here as opposed to the Active Directory section.
    If this should be moved, please let me know.

    Here's the start a series of articles that may help:
    http://blogs.msdn.com/b/taylorb/archive/2012/03/26/remote-administration-with-powershell-3-0-sessions-part-1.aspx
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • SharePoint Remote Powershell Session - Can't find the local farm

    Hi,
    I've been trying to configure a remote PS session to connect to a SharePoint Farm to create site objects.  I can get connected and load the SharePoint PS snap in successfully but when I try commands like Get-SPWeb all I get is an error "Cannot
    access the local farm".
    If I launch PS on the SharePoint server and add the snap in I can use the CMDLETs fine.  I've ensured PS remoting is enabled and granted access so that the client computer is authorised to connect to the SharePoint server.
    Here is the connection code I've used:
    $RunAsAccount = "domain\user"
    $RunAsPass = "password"
    $pass = $RunAsPass | ConvertTo-SecureString -AsPlainText -Force
    $credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $RunAsAccount, $pass
    enter-pssession -computername spserver.domain.local -credential $credentials
    Add-PSSnapin Microsoft.SharePoint.Powershell
    The connection user is a local administrator on the sharepoint server and is a dbowner of the sharepoint config and content databases (for testing) and also has shell access on the sharepoint config DB.
    Any ideas?
    Thanks,
    Tim

    Remoting isn't quite that nice.
    I believe you need to use an invoke-command to run the snapin on the destination server, or import the commandlets locally to slightly different names.
    To borrow the important section for your needs first you'd need to put the session into a variable for later use, then use the invoke-command cmdlet
    "$session = New-PSSession -computername "SPServer" -Authentication CredSSP -Credential $crd
    Start Remoting on you Client Computer
    Now your client computer is ready to actually create the session and import the SharePoint commands from the Server.
    The next command adds the SharePoint PowerShell commands to your session.
    Invoke-Command -Session $session -ScriptBlock{Add-PsSnapin Microsoft.SharePoint.PowerShell}
    Note, that at this point, you can run whatever administrative PowerShell commands you need to run by using the Invoke-Command -Session $session -ScriptBlock{} syntax."
    http://blogs.msdn.com/b/varun_malhotra/archive/2010/06/10/configure-power-shell-for-remote-use-of-sp-2010.aspx

  • How to run UNIX command to a remote SUN machine through Java from Windows

    Dear All:
    I want to write one Java program which will be run on my Windows Machine.
    My Java program will will login in a SUN machine remotely say telnet and run some command.
    I want all those command output in my client windows PC for futher processing.
    Can anyone help me doing this?
    BR,
    P. Gupta

    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class TelnetSocketDemo {
    static String list="";
    static String listArr[], hostArr[];
    static String host="", lhost="";
    public static void main(String[] args)throws IOException
    ExecuteUnixCmd obj=new ExecuteUnixCmd();
    // InetAddress localMachine = InetAddress.getLocalHost();
    // host=localMachine.getHostName();
    list=obj.ExecuteUnixCmdMain();
    int port=getPort(list,"Live");
    System.out.println(port);
    Socket sock = null;
    String prompt=">";
    String output = null;
    try
    // Connect to the PoleStar process.
    sock = new Socket("localhost",port);
    sock.setSoTimeout(60000);
    // Get the I/O streams for the socket.
    PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
    InputStream in = sock.getInputStream();
    // Get to the silent console port.
    // out.println("S");
    // readToPrompt(in,area);
    // Fetch the response to the command.
    out.println("list all");
    output = readToPrompt(in,prompt);
    //System.out.println(output);
    //out.println("quit");
    //output=readToPrompt(in);
    catch (Exception ex)
    String msg = "unable to get Connection for PoleStar";
    finally
    try
    // close socket
    sock.close();
    catch (Exception ex)
    System.out.println(output);
    private static String readToPrompt(InputStream in,String prompt)throws IOExcepti
    on
    byte[] mByte = null;
    int iStrt = 0, iLen = 2000, nBytes = 0;
    StringBuffer buf = new StringBuffer();
    String s = null;
    boolean bNotFinished = true;
    do
    mByte = new byte[2000];
    nBytes = in.read(mByte, iStrt, iLen);
    if (nBytes == -1)
    break;
    // lost our TCP/IP connection
    // bNotFinished = false;
    // Convert byte stream to a string
    s = new String(mByte, 0, iStrt + nBytes);
    if (prompt.equals("") == false)
    if (prompt.equals(">"))
    if (s.indexOf(0x04) != -1)
    bNotFinished = false;
    // the hub sends the prompt at the beginning and the end
    else if (s.indexOf(prompt) != -1)
    bNotFinished = false;
    buf.append(s);
    } while (bNotFinished);
    return buf.toString();
    public static int getPort(String list, String area)
    int port;
    String listArr[],hostArr[];
    String lhost="";
    listArr=list.split(",");
    for(int i =0; i < listArr.length ; i++)
    lhost=listArr;
    hostArr=lhost.split("#");
    if((hostArr[1].equalsIgnoreCase("connectDev20"))&&(hostArr[0].indexOf(area)!=-
    1))
    port=Integer.parseInt(hostArr[2]);
    return port;
    else
    continue ;
    return 0;

  • Powershell generic session and import this session in Exchange remote management session c#

    The situation :
    I am trying to make an application (c#-asp.net) to manipulate user's on an exchange server. The application will be on a different server than the exchange's one. So, to manipulate the data, I am using an "Exchange remote management session" created
    with c#. Exchange remote management session give access to simple powershell command like "New-Mailbox" and "Set-User" - This is good for simple task, but in my case, I have to do more complexe operations that will need some specific command
    that is not included in the default command. To access this command, I have to use some specific module like "ActiveDirectory". It is simple ? Only use "Import-Module" ! Not really, like I said, the "Exchange remote management session"
    is very limited with the command, and "Import-Module" is not allowed...
    So what we can do ?
    I read a lot about my problem, and the most "simple" (That I understand the theory) solution is something like :
    Start with a generic PS session, import the AD module, then connect to an Exchange management session and do an Import-PSSession and use implicit remoting for the
    Exchange management stuff.
    Given that I am pretty new to manipulate the Powershell with c#, I have no idea how to use this awesome solution in my code. So I am asking your help.
    Here's my current code :
    // Prepare the credentials.
    string runasUsername = @"MarioKart 8";
    string runasPassword = "MarioKart";
    SecureString ssRunasPassword = new SecureString();
    foreach (char x in runasPassword)
    ssRunasPassword.AppendChar(x);
    PSCredential credentials =
    new PSCredential(runasUsername, ssRunasPassword);
    // Prepare the connection
    var connInfo = new WSManConnectionInfo(
    new Uri("MarioKart8Server"),
    "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
    credentials);
    connInfo.AuthenticationMechanism =
    AuthenticationMechanism.Basic;
    connInfo.SkipCACheck = true;
    connInfo.SkipCNCheck = true;
    // Create the runspace where the command will be executed
    var runspace = RunspaceFactory.CreateRunspace(connInfo);
    // create the PowerShell command
    var command = new Command("New-Mailbox");
    // Add the command to the runspace's pipeline
    runspace.Open();
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);
    // Execute the command
    var results = pipeline.Invoke();
    if (results.Count > 0)
    System.Diagnostics.Debug.WriteLine("SUCCESS");
    else
    System.Diagnostics.Debug.WriteLine("FAIL");
    This code work great for simple task (like "New-Mailbox") ! But how can I create a "generic PS session" and then use this session in the "Exchange remote management session" ?

    Hi Vincent,
    Generally we can use the cmdlet "import-module" to import the AD module on DC (Domain Controller), and we can also create a exchange remote powershell session with the cmdlet new-pssession, for more detailed information to create exchange remote session,
    please refer to this article:
    Managing Exchange 2010 with Remote PowerShell
    In addition, to invoke powershell cmdlet in C#, please also try to save all the cmdlets to a powershell script (.ps1 file), then we can add the powershell script to C# like:
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);
    If I have any misunderstanding, please let me know.
    Best Regards,
    Anna Wang

  • Loadbalancing powershell session to Exchange Server 2013

    Hi all!
    I try to configure remote powershell session to Exchange server through hardware load balancer. For create session i use command like this:
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<load balancer virtual ip>/PowerShell/ -Authentication Kerberos
    And i receive error, because not exist SPN record for load
    balancer virtual ip.
    That username and service i should use for create SPN-record?
    And also i try connect via
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<load balancer virtual ip>/PowerShell/ -Authentication Negotiate
    and i receive HTTP 400 Bad request. I ask google about it, but not found something usefull. Have someone any ideas?

    Hi Cemeh,
    Thank you for your question.
    We could make sure the SPN has been registered by run “ADsiedit.msc” in the RUN, then we could connect to “Default naming context”, then we could check load balandce name properties if it has SPN. We could refer to the following link:
    https://msdn.microsoft.com/en-us/library/ms676922(v=vs.85).aspx
    Then if the issue persist, we could run the following command:
    $Session = New-PSSession -ConfigurationName Microsoft.PowerShell -ConnectionUri http://<load balancer virtual ip>/PowerShell -Authentication Kerberos
    There are some links we could refer to by the following link:
    Service Principal Names
    http://msdn.microsoft.com/en-us/library/ms677949(VS.85).aspx
    Kerberos authentication and troubleshooting delegation issues
    http://support.microsoft.com/kb/907272
    If there are any questions regarding this issue, please be free to let me know. 
    Best Regard,
    Jim
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]
    Jim Xu
    TechNet Community Support

  • Lync 2013 Remote Powershell

    Hi everyone,
    I have problem to run start-csclslogging through remote powershell. Here is the step that I have done
    First: install Lync debug tool (that includes snooper, ocslogger, etc..) and install Lync administrative tool (which includes Lync management powershell). I also copied the clsagent folder inside "C:\Program Files\Common Files\Microsoft Lync Server
    2013" from Lync Frontend server to my own laptop
    Next, I run this script to remotely connect to my frontend server:
    # get creds for remote environment
    $credential = get-credential "my username"
    # set session options to bypass the PKI checks - I trust the far side
    $sessionoption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
    #create new session
    $session = New-PSSession -ConnectionUri https://myfrontendserver/ocspowershell -Credential  $credential -SessionOption $sessionOption
    # assuming the above line worked, import the cmdlets needed for Lync
    import-pssession $session
    Everything works fine, i can run several Lync commands remotely (e.g. provision user account). However when I started to run the troubleshooting command like start-csclslogging -screnario IMandPresence, I faced below error message
    Start-CsClsLogging : Cannot validate argument on parameter 'Scenario'. Method not found: 'Void Microsoft.Rtc.ClsCommon.Settings.Initialize(Boolean)'.
    At line:1 char:30
    + Start-CsClsLogging -Scenario IMandPresence
    +                              ~~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [Start-CsClsLogging], Parameter BindingValidationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Rtc.Management.Cls.StartOcsLoggingCmdlet
    Your advise is much appreciated. Thank you

    Hi tdth,
    To better understand the issue, I would like to collect the following information for troubleshooting:
    1. Can you run the command on the Lync Server ?
    2. Do you have created any custom scenario ?
    3. Can you run the following command to capture the log?
    (Note: By default ClsController.exe is installed under "C:\Program Files\Common Files\Microsoft Lync Server 2013\ClsAgent". You need to start Lync Management Shell
    and access the location "C:\Program Files\Common Files\Microsoft Lync Server 2013\ClsAgent".)
    ClsController.exe -start -scenario IMAndPresence -Pools <Pool FQDN>
    Best regards,
    Eric
    1. Yes, I can run the command locally on FrontEnd server
    2. No. I know what problem you're talking about, but it's not because of Site-level scenario
    3. Same as question 1, if I run this command locally on Frontend server, it works. But I cannot run it from remote powershell session.

  • 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

  • Running commands on VMs remotely

    Hi Everyone
    New to all of this so please bear with me!
    Starting a new project and looking to compare between the use of Hyper V and ESXi.  
    The project is to grab vms regardless of state, turn them on and execute scripts stored on a vm drive. The script execution has to be performed / issued by a user. C# is the main underlying code but we can potentially put in references to use powershell
    scripts / whatever else if we can achieve this using hyper v.
    I know from doing a bit of reading on ESXi that we can do this using a number of ways - vmrun to start, stop and run commands on the actual vm itself. using other vmware libraries and APIs.
    I have read that powershell commands include starting vms, taking snapshots, shutting down vms but I was wondering if we can get into the actual VM remotely / somehow in-order to, for example, run a script which is stored on that VMs C drive.
    Has anyone tried this / is it do-able? -  I have had no luck finding any examples of what we need. 
    Kind Regards,
    Ashley

    I have a few things that I have done historically.
    Really, you have two options.  a WMI (API) call or a WinRM / PowerShell remoting call.
    The difference between the two is 1) security settings and 2) ease of use.
    For WinRM the security needs to be more open then WMI.  But, it is far easier to script as you simply open a remote session and you keep scripting along in the remote shell (the tricky part is pulling values back to the local session).  With WMI
    you always get the values back since you never spawn into another session.
    Below is a WinRM example of using WinRM and returning some value back:
    It executes a WMI command on the remote machine to fin the file I am looking for (as that is faster) and then I read the file with the script.
    # This block of script executes remotely and returns the content of hte CtxSta.config file.>
    $sta = invoke-command -Session $s -ScriptBlock {
    $staArray = get-wmiobject CIM_DataFile -filter 'Extension="config" and FileName="CtxSta"'
    # If IIS Integration is installed there could be multiples, this is the one that CSG is hard coded to use.
    foreach ($e in $staArray) {
    if ($e.Path -match "citrix\\system32") {
    $sta = $e
    get-content -path ([string]$sta.Name)
    # We have returned to local execution.
    foreach ($e in $sta) {
    switch -wildcard ($e) {
    "UID*" {
    $e = $e -replace "UID", ""
    $e = $e -replace "=", ""
    $e = $e -replace " ", ""
    $staId = $e
    $staId
    Brian Ehlert
    http://ITProctology.blogspot.com
    Learn. Apply. Repeat.

  • How can I Deny permissions to logon to Remote Desktop Session Host server in powershell script?

    I am need of some assistance please. I am a system admin and I am trying to create a script that will assist with the tedious tasks I have to do with disabling a user that no longer works for the company.
    I have created a script so far that will reset the users passwords and remove them from all groups (minus domain users).
    I am trying to make it where it will deny permissions to logon to Remote Desktop Session Host server as well as give full mailbox permission to the manager in Exchange Server 2010.
    I know with Exchange 2010, I will need to add the Powershell snapin. Is there a way for this to be added into the script? I am thinking to add the code:
    add-pssnapin Microsoft.exchange.management.powershell.e2010
    Is there another way to do this? Any help or recommendations would be much appreciated.
    $ou = Get-ADUser -SearchBase "<*OU info here*>" -Filter * |
    Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "<*Password here*>" -Force)
    foreach ($user in $ou) {
    $UserDN = $user.DistinguishedName
    Get-ADGroup -LDAPFilter "(member=$UserDN)" | foreach-object {
    if ($_.name -ne "Domain Users") {remove-adgroupmember -identity $_.name -member $UserDN -Confirm:$False} }

    Why not just disable the account?Why are you searching an OU foro users when you just want to terminate one user?
    You can remotely connect an exchange session and manipulate the mailbox permissions.  You do not load a snap-in except on the Exchange server.
    $Session=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://<FQDN of Exchange 2013 Client Access server>/PowerShell/
    Import-PSSession $Session
    # exchange commands here
    \_(ツ)_/
    We have a checklist we have to go through with the tasks listed. We have to keep to the account enabled until HR changes
    the status which is usually 30-90 days depending. Managers sometimes need to access the accounts to retrieve information, etc. We put the users in an OU; once we are given permission from the manager we move forward in the removal. 

  • Cannot load Exchange Online Protection commands in Remote PowerShell

    My colleagues and I cannot load the Exchange Online Protection commands in Remote PowerShell.
    It just loads the Exchange Online cmdlets.
    Where are we going wrong?
    PS C:\Users\jmorrison> $UserCredential = Get-Credential
    cmdlet Get-Credential at command pipeline position 1
    Supply values for the following parameters:
    PS C:\Users\jmorrison> $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.protection.outlook.com/powershell-liveid/
    -Credential $UserCredential -Authentication Basic -AllowRedirection
    WARNING: Your connection has been redirected to the following URI: "https://outlook.office
    365.com/powershell-liveid?PSVersion=4.0&realm={I've removed my domain name for security reasons}.co.uk "
    PS C:\Users\jmorrison> Import-PSSession $Session
    ModuleType Version   
    Name                               
    ExportedCommands              
    Script    
    1.0        tmp_4fnmyflw.she                   
    {Add-AvailabilityAddressSpac...
    PS C:\Users\jmorrison> Get-TransportRule
    Get-TransportRule : The term 'Get-TransportRule' is not recognized as the name of a
    cmdlet, function, script file, or operable program. Check the spelling of the name, or
    if a path was included, verify that the path is correct and try again.
    At line:1 char:1
    + Get-TransportRule
    + ~~~~~~~~~~~~~~~~~
    + CategoryInfo         
    : ObjectNotFound: (Get-TransportRule:String) [], CommandNotF
    oundException
    + FullyQualifiedErrorId : CommandNotFoundException

    I've moved MX records to EOP and seems to be fine all domain expect few.<o:p></o:p>
    I can see that problematic domain has "-" between domain names.<o:p></o:p>
    mydomain.com<o:p></o:p>
    mydomain-com.mail.protection.outlook.com --> has no problem, however<o:p></o:p>
    mydomain.usa.com<o:p></o:p>
    mydomain-usa-com.mail.protection.outlook.com having issue <o:p></o:p>
    when i checked in mx lookup it says MX record has NO A Record.<o:p></o:p>
    any suggestions<o:p></o:p>

  • Opening Remote Browser Session w/RT Client causes unopened VI from Project on Host computer to pop up and run

    I have a functional global variable (FGV) that runs on my RT target (LV 9.0f2) and is set via SubVI Node Setup to "open front panel when loaded" and Execution under VI Properties for the FGV is set to "Run when opened", "Allow debugging", & "normal priority".  The interesting thing that occurs happens when I have already opened the project it is contained in (but have not as yet opened any VIs) and then I establish a remote browser session with the already running real time startup application on the remote real time controller.  Everything works as expected, I can see my front panel in the browser showing that the application is running.  Once I begin to populate the controller's inputs with data, the data triggers a previously uncalled state of a subroutine that calls the FGV for the first time on the realtime system to start tracking the data.
    It is at this point that the actual VI on my host machine opens and runs locally.  I do have a web browser page available on the target machine that I can establish a session with but I have not opened it yet, and besides, this is the actual LOCAL VI that starts running.  It even stops running when I initiate the remote stop capability of my realtime application from my browser session.  The VI then remains open on my local machine.
    This only happens when the project is open on the machine I have begun the remote browser session on.  Is this a "feature" of LabVIEW? I haven't seen any problems as a result of this, but the "linking" behavior is a little disturbing because it seems like there is some background linkage happening here that might also cause other problems - what else is happening in the background, gremlins? (if you know what I mean)?
    By the way, my platform is Windows XP SP3, the browser is Mozilla Firefox 3.5.5, the application on the real time controller is taking about 25% of both processors (PXI-8106) capability and the data is NI XNET (PXI-8512 / 2) CAN related. 
    Bill

    Justin:
    What I am reporting on is pretty simple.  I have a VI that is self starting and runs when called on the Realtime platform.  While I am viewing the front panel of the calling VI using a remote web browser session, when the data that starts the VI on the remote platform begins to flow, the LOCAL VI on my laptop appears to open and appears to run LOCALLY.  This only happens if I have the project open containing the build specification for the project AND I have requested control of the top level vi from the web browser session.  I suspect that this is not expected behavior.  I have not tested it, but the VI that pops up like I have described is the only VI I have placed in the build specification under the "always included" category of source files. Upon closer examination I am noticing that the VI that pops up does NOT stay open when the upper VI is stopped remotely. 
    I guess this isn't really a problem, just not quite sure why it happens.
    Bill

  • Server running remote powershell instance

    Hello,
    I have just installed Exchange 2010 on a W2K8 R2 machine.
    It tells me: "specify server running remote powershell instance" , and I don't know which server has that installed.
    I am new to Exchange 2010.
    I supposed it was the first Exchange I installed (I have installed four servers (lab environment): 2 CAS+HUB + 2 Mailboxes).
    I used google and there are a lot of information regardind Remote powershell, but not about this prompt in Exchange 2010 that I can find.
    Thanks in advance!
    Luis Olías Técnico/Admon Sistemas . Sevilla (España - Spain)

    Ah - you are adding a remote forest to your current forest.  This is also how you link up Office 365.
    BUT
    If all you want to do is manage the Exchange install in you test AD then just expand the Exchange server On-premises in the left hand pane.  Does that work for you?
    Cheers,
    Rhoderick
    Microsoft Senior Exchange PFE
    Blog:
    http://blogs.technet.com/rmilne 
    Twitter:   LinkedIn:
      Facebook:
      XING:
    Note: Posts are provided “AS IS” without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

Maybe you are looking for