Executing ps script on remote machine with VBscript - powershell

I am attempting to execute a powershell script on 10.0.0.20 found at D:\path\script.ps1 with the parameter of 6.9.0 from 10.0.0.199 using VBscript. I believe I am on the right route with the following code but I'm not sure where to go from here. Any suggestions?
side note, it needs to run as administrator
sub main()
dim strComputer, strUser, strPassword
strComputer = "10.0.0.20"
strUser="userName"
strPassword="password"
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer (strComputer, "root\cimv2", strUser, strPassword)
objSWbemServices.Security_.ImpersonationLevel = 3
end sub
main

Enable PSRemoting on the remote system and invoke it that way, assuming that your workstation and the remote system are on the same domain, and your domain account has admin access to the remote system.
Invoke-Command -computer "10.0.0.20" -scriptblock {. d:\path\script.ps1}

Related

Powershell invoke-command multihopping

I have a question regarding multihopping in a windows environment.
Let's say I have a schedule running on Server A (Central Scheduler) which executes a command on Server B. This script contains a call to save files on a remote filer (UNC path, Server C). Hop 1 (from A to B) works well, hop 2 (from B to C) fails.
I already tested to save the files locally on server B, that works flawlessly.
I think there's a problem with the second hop. I remember reading something like this on a forum a while ago, but can't remember a solution.
In detail, the command looks like this:
$session = New-PSSession -computer ComputerName
$templatepath = "\\filerpath\"
Invoke-Command -Session $session -Scriptblock { powershell ovpmutil cfg pol dnl $Using:templatepath /p \BSH }
To clarify: Powershell gives me an "Access denied" when performing the second hop. I already enabled Credential delegation as described here:
Enabling Multihop Remoting
Any help is appreciated. Thanks in advance
The solution is a real pain in the backside if you ask me but here it is...
On the originating server (A):
Set-Item WSMAN:\localhost\client\auth\credssp -value $true
On the intermediate server (B):
Set-Item WSMAN:\localhost\client\auth\credssp -value $true
Open Group Policy editor on server A, navigate to:
Computer Configuration > Administrative Templates > System > Credentials Delegation
Enable these options:
Allow delegating fresh credentials
Allow delegating fresh credentials with NTLM-only server authentication
Both policies need to have server B added to the allowed list, wildcards are allowed. Note that if you use RDP from server A you'll also need to add TERMSRV/*
When running Invoke-Command from server A, include the -Authentication CredSSP param.
Note that if saving SecureStrings somewhere for the credential to connect to server C, you'll want to either use a fixed encryption (specify byte array) or plain text and convert it.

Powershell "screen" - keep the processes running even the connection is dropped?

I'm using enter-pssession to run scripts on remote servers. So I can login remotely to the servers. Run commands interactively, close the powershell console and later I can reattach the session and check the commands outputs.
Is there a Linux screen like functionality in powershell? I cannot use Windows remote desktop to connect the servers.
You can use Invoke-Command with -InDisconnectedSession, it will start session in asynchronous mode. After you can connect to this session, take data from it, etc. You can read more about this here.
You can create session, disconnect from session, connect back to it.
May be useful for you: New-PSSessionOption with -IdleTimeout.
-IdleTimeout:
Determines how long the session stays open if the remote computer does not receive any communication from the local computer. This includes the heartbeat signal. When the interval expires, the session closes. MSDN Link
I have recently run into double-hop issues with using PSSessions. What I did to work around that is to create a Session Configuration on the remote server that uses the -RunAs parameter to set the credentials that I need the commands on the remote server to be executed as. Then you connect to that session configuration on the remote server, and things should work as expected.
$MyCreds = Get-Credential ''
Invoke-Command -ScriptBlock {
Set-PSSessionConfiguration -Name "My Remote Config" -RunAsCredential $using:MyCreds -Force
} -ComputerName Server01
Then once the session configuration exists I can start a session using that config, and the whole double hop issue is null and void.
Now, mind you I do add some additional security, so that other people cannot use my session config, since that config has my credentials cached on the server (encrypted), and if they used that config they could do whatever they wanted as me. So to accomplish that I get my domain account SID, generate a SDDL line, and restrict access to the Session Config to only my account.
$Searcher = [adsisearcher]"(&(sAMAccountName=$($Creds.UserName.Split('\')[1]))(objectClass=user))"
$Results=$Searcher.FindOne().GetDirectoryEntry()
$MySID = new-object System.Security.Principal.SecurityIdentifier($Results.objectSid.value,0)|% value
$SDDL = "O:NSG:BAD:P(A;;GR;;;BA)(A;;GR;;;IU)(A;;GA;;;$MySID)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)"
$FQDN = $Server.ServerName,$Server.Forest -join '.'
$MySessionName = "DoubleHop-{0}" -f $MyCreds.UserName.Split('\')[1]
Invoke-Command -ScriptBlock {
Register-PSSessionConfiguration -Name $using:MySessionName -RunAsCredential $using:MyCreds -Force -SecurityDescriptorSddl $using:SDDL
} -ComputerName $FQDN -ea 4

Invalid computer name error with remote execution of PowerShell script

I am trying to execute some PowerShell code in a remote computer using the following:
$session = New-PSSession -Credential "myDomain\myUserName" -ComputerName "remoteCompName"
$result = Invoke-Command -Session $session -ScriptBlock {
New-Item -type file C:\test10.txt
}
I am prompted to enter my password in a GUI. I do that. It then errors out with:
New-PSSession : One or more computer names are not valid. If you are
trying to pass a URI, use the -ConnectionUri parameter, or pass URI
objects instead of strings.
I replaced the computer name with the FQDN. Still no luck. What is going on here?
There are other questions on stackoverflow on executing PowerShell scripts on remote machines of course but none address this error.
BTW, the machine is part of the domain and is running.
Additional info added later [EDIT]
Things to know:
The machine is part of the domain and is running.
I checked if PS remoting is enabled. It was.
I checked if WinRM is running. It is.
The remote machine is a VM and it is a 2012 R2.
Here is what I've tried:
I replaced the computer name with the FQDN. Still no luck.
I removed the credential parameter
I tried another remote machine (also a VM)
I tried another source machine, i.e. the machine I am running the command from)
Thanks!
-Rohan.
When I use a remote machine with a name that is just alphanumeric (no underscores, dashes, etc.), it works! The name of all machines I tried before had leading '_' in them. That was the cause of the error. (The answer was suggested by Rhys W Edwards on the Windows PowerShell TechNet forum, which is within Windows Server forums).
Just put your ComputerName to braces like this {Remote_Computer_Name}

Grabbing system product keys

So I'm trying to use the PS script found at http://gallery.technet.microsoft.com/scriptcenter/Get-product-keys-of-local-83b4ce97#content to pull Windows product keys from my domain remotely. However, when it hits a host it returns Exception calling “OpenRemoteBaseKey” with “2″ argument(s): “The network path was not found” instead of the product key. It should also be noted that this works locally. After poking around at the internals of the script, it seems like the offending line is
$remoteReg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Computer)
Research (because I'm totally new to PoSH) indicates that this type of error gets thrown when remote registry access isn't working. Trying to hook into the registry on my test target via regedit shows that I need to have Windows Firewall: Allow inbound remote administration exception set to enabled in Group Policy. I set it and then pulled the updated policy down to the same result. What other stuff might be getting in the way of my connection?
I would recommend using PSRemoting over using the remote registry. Assuming this is set up, all you would have to do is:
$computers = #('localhost')#list of computers
#unless you are currently logged in as a domain admin
# you will need to provide credentials
$cred = Get-Credential domain\administrator
Invoke-Command -Credential $cred -ComputerName $computers -ScriptBlock {
function Get-ProductKey{
#from http://gallery.technet.microsoft.com/scriptcenter/Get-product-keys-of-local-83b4ce97
}
get-ProductKey
}| ft Computername,OSDescription,OSVersion,ProductKey
This will print out the following output:
Computername OSDescription OSVersion ProductKey
------------ ------------- --------- ----------
%name% Microsoft Windows 8 Pro 6.2.9200 XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
I used the following command through powershell, ran it as admin:
wmic /user:jc1_admin /node:pc00202 os get "SerialNumber"

create a function with proper scope

I need to create a script to authenticate to a remote PC and access to PS console. It actually works, but I need to execute a number of commands when I need to terminate this session.
So I create a function STOP to be called to terminate the session, but it can't be used.
Is this a problem of scope (because it's inside an if statement)? If I manually create the same function and then I try to call it... It works!
# get connection parameters
$credential = Get-Credential -Credential xxx
$remote_PC = Read-Host "Insert the server name or IP (Q to abort): "
# connect
if (someKindOfCheck) {
Enter-PSSession -ComputerName $remote_PC -Credential $credential
# some commands
function STOP {
Exit-PSSession;
# some commands
}
}
I've come across a similar issue before, and I resolved it by creating a New-PSSession and assigning it to a varialbe, I then use the Invoke-Command with -Session option to execute the required commands.
Enter-PSSession is only for interactive use (once you've entered that session it only takes input from the console).
The only way I can think of that would make this work "automagically" would be to create a custom remoting session on the target machine that implements a proxy function for Exit-PSSession, and put your commands in that function.