Run Powershell in remote computers

Hi All,
I want to run Powershell function in a remote computers in AD 
Here are the steps that i take but i got some errors 
* I Import the ADComputer from Active directory 
Get-ADComputer -Filter * -Property * | Select-Object Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion | Export-CSV C:\Users\Administrator\Documents\AllWindows.csv -NoTypeInformation -Encoding UTF8
*Then I create a script to run the function I got from net 
$FilePath = "C:\Users\Administrator\Documents\AllWindows.csv"$ComputerName = Import-Csv -Path $FilePath -Delimiter ","foreach($CompName in $ComputerName){Invoke-Command -ComputerName $PSItem.Name -ScriptBlock ${function:Get-WindowsKey}}
But when i run above gives the following error
Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\Administrator\Desktop\GetWinKey.ps1:9 char:30
+ Invoke-Command -ComputerName $PSItem.Name -ScriptBlock ${function:Get-WindowsKey ...
+                              ~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
Following is the function i run to get windows keys
function Get-WindowsKey {    ## function to retrieve the Windows Product Key from any PC    param ($targets = ".")    $hklm = 2147483650    $regPath = "Software\Microsoft\Windows NT\CurrentVersion"    $regValue = "DigitalProductId"    Foreach ($target in $targets) {        $productKey = $null        $win32os = $null        $wmi = [WMIClass]"\\$target\root\default:stdRegProv"        $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue)        $binArray = ($data.uValue)[52..66]        $charsArray = "B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9"        ## decrypt base24 encoded binary data        For ($i = 24; $i -ge 0; $i--) {            $k = 0            For ($j = 14; $j -ge 0; $j--) {                $k = $k * 256 -bxor $binArray[$j]                $binArray[$j] = [math]::truncate($k / 24)                $k = $k % 24            }            $productKey = $charsArray[$k] + $productKey            If (($i % 5 -eq 0) -and ($i -ne 0)) {                $productKey = "-" + $productKey            }        }        $win32os = Get-WmiObject Win32_OperatingSystem -computer $target        $obj = New-Object Object        $obj | Add-Member Noteproperty Computer -value $target        $obj | Add-Member Noteproperty Caption -value $win32os.Caption        $obj | Add-Member Noteproperty CSDVersion -value $win32os.CSDVersion        $obj | Add-Member Noteproperty OSArch -value $win32os.OSArchitecture        $obj | Add-Member Noteproperty BuildNumber -value $win32os.BuildNumber        $obj | Add-Member Noteproperty RegisteredTo -value $win32os.RegisteredUser        $obj | Add-Member Noteproperty ProductID -value $win32os.SerialNumber        $obj | Add-Member Noteproperty ProductKey -value $productkey        $obj    }} 
What i want is to run the Get-WindowsKey function in all AD computers 
Thanks

The error tells you what is wrong, try changing this -
Invoke-Command -ComputerName $PSItem.Name to thisInvoke-Command -Computername $Compname.Name
You need to use the variable you declare in the foreach loop.

Similar Messages

  • Running powershell on remote machine

    how do I run a script that is currently on my desktop to multiple remote machines? Does the script needs to be on the remote machine before it can be executed? wsman is already enabled on all remote machines

    Hi Jon,
    I’m writing to just check in to see if the suggestions were helpful. 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 Wang
    TechNet Community Support
    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 commands on remote Hyper-V host in different domain/network with powershell

    Hi experts,
    My Setup: Windows Server 2012 R2 / SCVMM 2012 managing localhost and other Hyper-V hosts
    I need to run a script on the remote Hyper-V Host which is in different domain/workgroup using powershell.
    I have tried
    Invoke-SCScriptcommand cmdlet. But I am getting the below error
    Error (2917)
    Virtual Machine Manager cannot process the request because an error occurred while authenticating MY-PC-15.mydomain.local. Possible causes are:
    1) The specified user name or password are not valid.
    2) The Service Principal Name (SPN) for the remote computer name and port does not exist.
    3) The client and remote computers are in different domains and there is not a two-way full trust between the two domains.
    The network path was not found (0x80070035)
    I tried the 'Run Script Command' option in the Host tab in VMM. But getting the same error.
    Checked that it uses the 'Invoke-ScScriptcommand' PS cmdlet.
    Could someone explain how to run scripts on remote Hyper-V host in different Domain/Perimeter network ?
    Regards,
    Saleem

    Hi Saleem,
    Please try to follow the article below to regarding using command "enter-pssession" across domains :
    https://social.technet.microsoft.com/Forums/windowsserver/en-US/f60a29ef-925e-4712-9788-1f95e12c8cfc/forum-faq-introduce-windows-powershell-remoting?forum=winserverpowershell
    (I tested it in my lab )
    Best Regards,
    Elton Ji
    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 Subscriber Support, contact [email protected] .

  • How can get value of registry DWORD value of remote computers with powershell

    HI
    I am using below script to get registry of remote computers with powershell but not desired result.
    $computers = Import-Csv 'C:\New folder\dclist.csv'
    $key = "SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
    foreach ($computer in $computers)
    Get-RegDword -ComputerName $computer -Key $key -Value IsInstalled
    As I have installed remoteregistry pssnapin a well..
    Also How can i get this from Invoke-Command ............
    Please help or guide me 

    This script may help (I haven't used it personally, but I know that many people have used it and thanked Jason for coming up with it):
    http://gallery.technet.microsoft.com/scriptcenter/Enable-PSRemoting-Remotely-6cedfcb0
    You can also configure remoting across your entire domain via GP:
    http://www.briantist.com/how-to/powershell-remoting-group-policy/
    http://blog.powershell.no/2010/03/04/enable-and-configure-windows-powershell-remoting-using-group-policy/
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • PST search on remote computers

    Hi,
    I am seeking for a pst search in VB or dos to locate any pst on all drives on remote computers that will record pst file + size, inc username or computer name and log all this information to a central csv or txt file on a network.....please help.

    To get the most mutable results, you can use this PowerShell script.  You will need to provide a list of computers in a text file with each computer on a separate line.
    Get-Content computers.txt |
    %{Get-ChildItem "\\$_\c$" -Include *.pst -Recurse} |
    Select Name,Directory,Length,LastAccessTime,LastWriteTime,CreationTime |
    Export-Csv C:\results\PSTfiles.csv -NoTypeInformation
    This assumes that you are only searching the C: drives of the computers.  As noted, this script will take a long time to run based on the number of computers that you are running it against.
    Rich Prescott | Infrastructure Architect, Windows Engineer and PowerShell blogger | MCITP, MCTS, MCP
    Engineering Efficiency
    @Rich_Prescott
    Windows System Administration tool 2.0
    AD User Creation tool

  • Hi I am looking for a way to have trace32 open multiple files on remote computers

    Simply put I am looking for someone who could afford to give me a basic script (vbs) that I could run from an elevated command prompt. It would need to be available for me to type in the name of a remote computer or (mulitple if possible) and also
    allow me to choose log files to open or multiple files and then open them using trace 32. Hopefully it would detect the available log files and show me what is available to choose to open... anyone know of such a thing or know how to go about setting up something
    like this for people to use?
    EDIT
    I was able to create a basic script to do what I wanted but I want to be able to add wildcards for the rollover logs... Can someone suggest the easiest way to do that as I am not sure how to add the wildcards directly before the .log
    here is the script.
    ' ******Created by Luis Delgado*********
    'This script will get a remote computers .log files depending on which documents you enter in the "files to open on remote computer using trace32" section
    'Get and open log files on remote Computer
    on error resume next
    Set WshShell = Wscript.CreateObject("Wscript.Shell")
    strcomputer   = inputbox("Enter remote computer name or leave as localhost for this computer","Get log files from a remote computer with Trace32","Localhost")
    If strComputer = "" Then
      WScript.Quit
    End If
    'Opens trace32
    wshShell.run "C:\Program Files\ConfigMgr 2007 Toolkit\CCM Tools\Trace32.exe"
    'Files to open on remote computer using trace32
    wshShell.Run "\\" & strcomputer & "\c$\Windows\System32\CCM\Logs\datatransferservice.log"
    wshShell.Run "\\" & strcomputer & "\c$\Windows\System32\CCM\Logs\ccmexec.log"
    wshShell.Run "\\" & strcomputer & "\c$\Windows\System32\CCM\Logs\locationservices.log"
    !!!!NOTE!!!
    What I need is for any file that starts with datatransferservices, ccmexec, or locationservices to open in trace32
    my thought would be place a wild card in its respective spots but it does not work see below
    wshShell.Run "\\" & strcomputer & "\c$\Windows\System32\CCM\Logs\datatransferservice*.log"
    wshShell.Run "\\" & strcomputer & "\c$\Windows\System32\CCM\Logs\ccmexec*.log"
    wshShell.Run "\\" & strcomputer & "\c$\Windows\System32\CCM\Logs\locationservices*.log"

    The roll over logs all have the same name exact the extension is .lo_ , So.. I'm not sure what you are looking for.
    Garth Jones | My blogs: Enhansoft and
    Old Blog site | Twitter:
    @GarthMJ

  • How to Find Which Programs running in my Domain Computers

    How to Find Which Programs running in my Domain Computers.

    In addition, there are other third tools you can use. Here is a script from the TechNet Scripting Gallery:
    List All Installed Software
    Returns a list of all software installed on a computer, whether or not by Windows Installer. This script reads installed applications from the registry. (See Richard Mueller's comment on how to output it to a CSV file)
    http://gallery.technet.microsoft.com/scriptcenter/8035d5a9-dc92-436d-a60c-67d381da15a3/view/Discussions
    Of course that's just running it against one computer. There's also a script in the above link (scroll to the bottom) that will find installed software of a list of computers in a network and also detect the defined forbidden installed software, and
    another script that will uninstall that software remotely.
    Overall however, if you want to do this network wide with much a much easier method (although more complex to setup), I agree with using SCCM or Spiceworks. There is also Altiris, and a number of other third party solutions that you can use.
    Maybe if you can provide more specific information on the end result of the solution you are looking for, we can provide more specifics to help you.
    Ace Fekay
    MVP, MCT, MCSE 2012, MCITP EA & MCTS Windows 2008/R2, Exchange 2013, 2010 EA & 2007, MCSE & MCSA 2003/2000, MCSA Messaging 2003
    Microsoft Certified Trainer
    Microsoft MVP - Directory Services
    Complete List of Technical Blogs: http://www.delawarecountycomputerconsulting.com/technicalblogs.php
    This posting is provided AS-IS with no warranties or guarantees and confers no rights.

  • Issue Binding remote computers

    OK, have Advanced Leopard Server running, DNS and Open Directory setup. Can Bind local computers. Tried binding remote computers and does not see/find server in Directory Utility... yet I can sign in and mount NFS shares. Does a specific port need to be open in firewall to do the binding? - Lewis

    Binding is largely for login. Yes some management settings, like printers, can be passed through this way.
    To print from home you should be using a VPN. The Internet is not a safe place these days. VPN creates a virtual tunnel between home and the office and you can imagine a virtual Ethernet cable passing through that tunnel.
    I think a combination of Mobile accounts and VPN may be the deal for you. You might not even need mobile accounts if your users have their own Mac and are already using a local account.
    VPNs are meant to be the only entry point on to your network. So once you have a VPN setup then your Internet connection should only allow VPN traffic in and nothing else, e.g. LDAP.
    Ok, two basic choices for VPNs... either your router is fancy enough to have its own VPN feature or you can setup your Leopard Server to be your VPN server. The router would then need to be configured to route incoming VPN requests to your Mac server. All other types of traffic pass through the VPN.
    This isn't the place for detailing exact steps for this. It would get long and complicated and there are specific info needed about your actual setup. I have to refer you to the manuals in the first instance:
    http://images.apple.com/server/macosx/docs/NetworkServices_Admin_v10.5_2ndEd.pdf
    http://images.apple.com/server/macosx/docs/UserManagementv10.5.mnl.pdf
    Other recommended reading:
    Mac OS X Support Essentials v10.5 ISBN-13: 978-0321489814
    Mac OS X Server Essentials v10.5 ISBN-13: 978-0321496607
    Leader-led training:
    http://training.apple.com/itpro/leopard101
    http://training.apple.com/itpro/leopard201
    Trust me... you will feel so enlightened.

  • Running powershell cmdlets from windows 7 against windows 2003

    what are the requirements for running PowerShell from windows 7 against windows 2003 server in a different domain?
    dhomya

    Hi Dhomya,
    If you mean Powershell Remoting, and if the domains don't have trust relationship, you can configure the setting "WSMan:\localhost\Client\TrustedHosts".
    To configure Powershell remoting, please also check this article:
    [Forum FAQ] Introduce Windows Powershell Remoting
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,                                 
    Anna Wang
    TechNet Community Support
    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 powershell command in app part on submitting item in O365 Sharepoint list.

    I need to fire an powershell command through app part as soon as i have submitted details or form on the list.
    As powershell command requires inputs, i have created list and a form into it, i mapped the column with the powershell input, but the commands is not running or firing, please help.
    Regards
    Mohit Jain

    Hi,
    According to your description, my understanding is that you want to run a Powershell command when submitting a form on the list to create mailbox for user.
    As your environment is Office 365, I suggest you can create a web service to call the PowerShell Command using C#. Then in the office 365 list, you can create a remote event receiver to trigger the web service to
    achieve it.
    Here are some detailed articles for your reference:
    http://msdn.microsoft.com/en-us/library/ms464040%28v=office.12%29.aspx
    http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
    http://msdn.microsoft.com/en-us/library/office/jj220043(v=office.15).aspx
    Best Regards
    Forum Support
    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 Subscriber Support, contact
    [email protected]
    Zhengyu Guo
    TechNet Community Support

  • Passing Credentials When Reading Performance Counters on Remote Computers; Systems.Diagnostics namespace

    Hello,
    I am working on a website where I need to read a few performance counters on remote computers.
    I'm using the System.Diagnostics namespace and the following is a snipet of my code:
    ****************  CODE  *********************************************************
     Try
                With perf_process
                    .MachineName = Hostname
                    .CategoryName = "Process"
                    .CounterName = "Private Bytes"
                    'Write entry to log here
                    tmp_working_set = perf_process.NextValue()
                    txtWorkingSet.Text = tmp_working_set
                    Select Case tmp_working_set
                        Case Is > 80000000
                            working_set_status = "Red"
                        Case 40000000 To 80000000
                            working_set_status = "Green"
                        Case 1000000 To 40000000
                            working_set_status = "Yellow"
                        Case Else
                            working_set_status = "Error"
                    End Select
                    If working_set_status = "Error" Then
                        txtWorkingSet.BackColor = Drawing.Color.Red
                        txtWorkingSet.Text = String.Format(CultureInfo.InvariantCulture, "{0:0,0.0}", working_set_status)
                    Else
                        txtWorkingSet.Text = String.Format(CultureInfo.InvariantCulture, "{0:0,0.0}", tmp_working_set)
                        txtWorkingSet.Text = tmp_working_set
                    End If
                End With
            Catch
                ErrMsg = ("Error reading the Working Set (memory) counter on " & Hostname & "." & vbCrLf & "Error number is " & Err.Number & vbCrLf & "Error description:
    " & Err.Description)
                MsgBox(ErrMsg)
                Write_Log_Entry(Now(), ErrMsg)            
                ErrMsg = ""
            End Try
    ****************  CODE  *********************************************************
    I usually end up with an "Access Denied" error because the account I'm running under does not have the proper permissions on the remote computer to read the counters.
    How can I pass and connect to the remote computer with a different set of credentials that have access to the counters?
    Exactly what permissions do I need to access the remote counters?  I can read them on some of my test computers and on others, I get the "Access Denied" error.
    Thanks in Advance,
    DetRich
    DetRich

    http://forums.asp.net/
    The ASP.NET forum is probably where you need to post.

  • Run Powershell as Daemon

    Hi guys!
    Today i'm going mad!
    Is it possible to run powershell script as a daemon?
    I have some confused ideas so it's better if i tell you what's in my mind:
    I need to create a message (something like keep attention) if someone open some files with particular extensions from a folder into fileserver.
    I think: maybe powershell can read directly from fileserver what kind of files are open and who open those files!
    But I can't run script one time only, i need to keep script running.
    Ok, maybe scheduling i can resolve the last thing but please tell me if the underlined things are possible please!
    A

    Hi A,
    I find this function which can help you get the open files and the user on file server:
    function get-openfiles{
    param(
    $computername=@($env:computername),
    $verbose=$false)
    $collection = @()
    foreach ($computer in $computername){
    $netfile = [ADSI]"WinNT://$computer/LanmanServer"
    $netfile.Invoke("Resources") | foreach {
    try{
    $collection += New-Object PsObject -Property @{
    Id = $_.GetType().InvokeMember("Name", ‘GetProperty’, $null, $_, $null)
    itemPath = $_.GetType().InvokeMember("Path", ‘GetProperty’, $null, $_, $null)
    UserName = $_.GetType().InvokeMember("User", ‘GetProperty’, $null, $_, $null)
    LockCount = $_.GetType().InvokeMember("LockCount", ‘GetProperty’, $null, $_, $null)
    Server = $computer
    catch{
    if ($verbose){write-warning $error[0]}
    Return $collection
    Refer to:
    Viewing open files on a file server from powershell.
    And if you want to send message to remote server, you can try the cmd "msg /server:servernamehere * /v msggoeshere".
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang

  • Issue with running powershell script in pssessions

    Hi Everyone,
    I am trying to run powershell script from remote machine using below commands
    C:\Users\user>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
    -command "$s= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
    http://Exchservername/PowerShell/ -Authentication Kerberos ; Import-PSsession $s; "C:\Failback.ps1"
    and Below is the failback.ps1.
    $mbxs = Get-MailboxDatabase | Sort Name
    ForEach($mbx in $mbxs)
    $MBdb=$mbx.Name $ServerHosting=$mbx.Server.Name
    if($mbx.activationPreference.value -eq 1)
    If ($ServerHosting -ne $ActivationPreference.Key.Name) 
    Move-ActiveMailboxDatabase $MBdb -ActivateOnServer $ActivationPreference.Key.Name -confirm:$False 
    Below is what i am getting.

    What is your question?  Are you pointing out the yellow text?  This is normal, and appears every time EMS is opened.
    I should also point out that Microsoft provides a script to re-balance databases, if that's what you're trying to accomplish:
    You can use the RedistributeActiveDatabases.ps1 script to balance the active mailbox databases copies across a DAG. This script moves databases between their copies in an attempt to have an equal number of mounted databases on each server in DAG. If required,
    the script also attempts to balance active databases across sites.
    https://technet.microsoft.com/en-us/library/dd335158(v=exchg.141).aspx
    Mike Crowley | MVP
    My Blog --
    Baseline Technologies

  • Start and stop windows service for multiple remote computers

    Hello,
    Can someone show me how to Start and Stop windows service for multiple remote computers using Command Prompt or PowerShell or even Java?
    Thank you

    You asked a pure Windows related question at a pure Java related forum. We have advised you to look for a Windows related forum to post the question. Nothing special. It's like asking a car mechanican to help you with your migraine, he would advise you to look for a general practitioner.
    But why are you so surprised and negative about this answer after all? Don't we have to help you? Don't you appreciate help? So be it then, but please stay away then if you keep this attitude.

  • Hi, I activated my CS6 in 2012 under my student licence and still using it. I've heard that you can't run CS6 on multiple computers. How do I transfer it from one computer to another as I am switching computers?

    Hi, I activated my CS6 in 2012 under my student licence and still using it. I've heard that you can't run CS6 on multiple computers. How do I transfer it from one computer to another as I am switching computers?

    Hi,
    first, I'm not Adobe's "slave" as you might to accuse me. Most of the posters here are users like me.
    I only can repeat that what I found in Adobe's help sites, as I wrote above. You are free to figure out the "real" truth and - the best would be - you may contact Adobe directly, here are - I'm sure you know them -  the links I would use: http://helpx.adobe.com/support.html  and http://helpx.adobe.com/contact.html.
    Hans-Günter

Maybe you are looking for

  • IPad4/iPhone5 won't print anymore

    When I first got the iPhone5 and iPad4, they came with IOS6. At that time they worked just fine with my CM1415fnw color LaserJet MFC. But that stopped once they got updated to IOS6.0.1. Now all I get is a printer halt saying that the paper won't feed

  • Is it possible to modify the Calendar object to only show working days?

    Is there a way to configure the Calendar selection, duration calculations, and notification dates in the system to only include working days (i.e. holidays and weekends are not counted and not available for selection)? This is particlular for Purchas

  • Massdeletion of messages in ME9F

    Hi all We have a lot of messages in ME9F. We want to delete those messages but unfortunately we haven't found a way how we perform a mass deletion in ME9F. The only way is to click on each message then go to "message details", click on the message an

  • Why does this query run slow ??

    hi , i have the following query SELECT   PT.PT_ID,   PCD_INST.CALL_PCD_NAME,   RC.RC_ID,   RC.RC_TITLE,   PCD.PCD_TITLE,   RC.E_TYPE FROM   PT,   PCD_INST,   RC,   PCD,   PCD_INST_RS WHERE   ( PT.PT_ID = PCD_INST.PCD_ID  )   AND  ( PCD.PCD_ID = PCD_I

  • I am trying to get my system preferences out of the trash, but my drag and drop is not working.

    I just can't find the answer anywhere.