Create folder with WMI with alternate credentials - powershell

I have a PowerShell script to create a folder on a remote computer with WMI. But I need to run this with alternate credentials. Normally I would just add -credential $cred to the command but I don't know where to put it in this case.
$computer = "COMPUTERNAME" # add the computername where the folder needs to bee created
$pathname = "PATHNAME" # add the path and foldername to be added
# Start local process with help of WMI
$p = [WMIClass]"\\$computer\root\cimv2:Win32_Process"
$p.Create("cmd.exe /c md $pathname") # run CMD to execute the action

Related

Using Powershell to check proxy setting on remote machine

So i know I can't use Netsh because WinRM is disabled/access denied on my network.
I cant invoke etc.
So I'm trying to figure out a way to take a list of computer names and get the proxy from the machines.
So, my idea is to take the list I have on a \share, and foreach ($pc in $list) I would copy over a .cmd file from the same share. that .cmd file just runs a powershell script from the share, on that remote machine.
So copy a cmd to remote machine. Run cmd on remote machine, that cmd just runs the powershell script that gets the proxy from the registry, and then writes the machine name and the proxy to a file on the share.
But,
I'm getting a blank output tho. So, weird.
Here's the script that runs on the remote machine:
Set-ExecutionPolicy Unrestricted -Force
$proxy = (Get-ItemProperty
'Registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings') | Select-Object AutoConfigURL
"$env:computername $proxy" |
Out-file -filepath "\share\Proxy\IEproxylistResolved.csv"
The problem is that I get empty file in IEproxylistResolved.csv its 3am and I'm prob just half dead in the head but could use a fresh perspective.
Have you tried this:
Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key
"Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Value AutoConfigURL
Source

writing a powershell script to relay commands over two servers

I have been working on getting a script running that runs from a main domain controller. I want to be able to run the script from this domain controller and have it invoke some commands on a varied amount of remote servers which in turn copies files from a NAS on the same network to a local directory on each server. I use credentials from a securecard that I pass in to elevate privileges but I cannot seem to get it to copy the files down unless I execute the commands on the server itself. If I can get powershell to remotely execute these commands and perform the action then I would be all set.
Here is what I have come up with so far, please let me know what might help get this going for me. I would appreciate any help provided.
# Sets the variable for the source file location (c:\temp\ThisFile.exe)
#$Source = "\\nas\Applications\devapp\autononomous\v2\.exe"
$Source = "c:\temp\redirect"
# Sets the variable for the destination file location
$Destination = "temp"
# Sets the variable for application
$Application = "REDIRECT"
# Sets the variable for the remote destination file location
$Remote_Destination = "c:\$Destination\$Application"
# Sets the variable for the remote command to be executed
$Remote_Command = "regedit /s $Remote_Destination"
# Pass in the credentials you will be using to be able to copy from
one server to another, otherwise it will attempt to use local credentials.
$Credentials = get-credential
# Read in servers from text file and execute script
$Servers = Get-Content c:\temp\PowerShell\Servers.txt | ForEach-Object {
Write-Host "Installing" $Application "on server" $_
Copy-Item -Path $Source -Destination \\$_\c$\$Destination -recurse -force -Credential $Credentials
Invoke-Command -ComputerName $_ -ScriptBlock {
Param($Remote_DestinationR, $Remote_CommandR)
cmd.exe /c if not exist "c:\app\v2" mkdir "C:\app\v2"
cmd.exe /c xcopy /E /I /Y "C:\temp\redirect\home" "C:\app\v2\home"
} -Argumentlist $Remote_Destination, $Remote_Command
}

Set Executable's Working Directory When PowerShell Remoting

I'm using PowerShell remoting to execute an exe file on a remote server. The problem is that the exe needs to have its Working Directory set to the directory that the exe is in for it to run properly. If I run the exe locally (on the server) from a command prompt it works fine, and if I use Enter-PSSession (from my workstation) and then use Start-Process -FilePath [PathToExe] -WorkingDirectory [DirectoryPath] that works fine, but if I use Invoke-Command -ComputerName [Blah] -ScriptBlock [MyScriptBlock] or $session = New-PSSession -ComputerName [Blah]; Invoke-Command -Session $session -ScriptBlock [MyScriptBlock] (from my workstation) then the working directory does not get set.
This is what [MyScriptBlock] looks like:
$scriptBlock = {
param($version, $database)
$hubSyncronizerExeDirectoryPath = "C:\inetpubLive\ScheduledJobs\$version\"
$hubSyncronizerExePath = Join-Path $hubSyncronizerExeDirectoryPath 'Test.exe'
Set-Location -Path $hubSyncronizerExeDirectoryPath
Get-Location
Write-Output "$version $database"
Start-Process -FilePath $hubSyncronizerExePath -WorkingDirectory $hubSyncronizerExeDirectoryPath -ArgumentList '/database',$database
}
I've also tried using Invoke-Command instead of Start-Process, but it has the same effect; the Working Directory does not get set.
I've verified this by using the SysInternals Process Explorer, right-clicking on the process and choosing Properties. When I launch it locally or use Enter-PSSession, the Command Line and Current Directory properties are set, but not when using New-PSSession or just Invoke-Command with ComputerName.
I'm using both Set-Location and setting the -WorkingDirectory, which are the 2 typical recommended approaches for setting the working directory, and Get-Location does display the expected (server's local) path (e.g. C:\inetpubLive\ScheduledJobs\1.2.3.4). I'm guessing that this is just a bug with PowerShell (I'm using V4 on workstation and server), or maybe there's something I'm missing?
UPDATE
It turns out that the working directory was a red herring (at least, I think it was). For some reason everything works fine if I called my executable from a command prompt.
So in my Invoke-Command (I replaced Start-Process with Invoke-Command), changing this:
& ""$hubSyncronizerExePath"" /database $database
to this:
& cmd /c ""$hubSyncronizerExePath"" /database $database
fixed the problem.
Thanks for all of the suggestions guys :)
Try looking at New-PSDrive and see if that helps
I guess you'll want something like
New-PSDrive -Name WorkingDir -PSProvider FileSystem -Root "\\RemoteServer\c$\inetpubLive\ScheduledJobs\1.2.3.4"
CD WorkingDir:
I assume you should be able to amend your script to include and put in the $version variable in to the path on the New-PSDrive command...
Not certain this will do what you need it to do, but it's the first thing that sprang to mind...
Alternatively, try amending your script as follows:
$hubSyncronizerExeDirectoryPath = "\\remoteserver\C$\inetpubLive\ScheduledJobs\$version\"

How do I start remote desktop from PowerShell?

How do I start an RDP session from powershell? I'm looking to avoid a custom script because I work at an MSP and end up remoting into machines across various domains in a day and so maintaining a selection of scripts across each is not trivial (unless you have a solution to that for me).
Same as in command line, you can launch the RDP client as so:
mstsc /v:10.10.10.10:3389
From your desktop, you can start an RDP session pointing to a remote system with this:
Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "/v:$machinename"
Where $machinename is the name of the remote system. You will be prompted for credentials.
Here it is in function format. As alorc said. Paste this into your $profile
function Start-RDP ($computername)
{
Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "/v:$computername"
}
Connection settings are stored in .rdp files. There is no need to specify a computer name and list other settings in the code.
Connect Hyper-V with settings from .rdp file:
$hyperv = Get-VM -Name "VM-Name"
if($hyperv.State -eq "Running") {
Write-Host "Hyper-V is Running."
Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "$env:userprofile\Documents\RDP-Name.rdp"
} else {
Write-Host "Hyper-V is Stopped."
Start-VM -Name "VM-Name"
Start-Sleep -Seconds 6
Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "$env:userprofile\Documents\RDP-Name.rdp"
}
Well, for the beauty of this whole process, create a .vbs file in the same folder that calls your .ps1 file in invisible mode.
Set objShell = WScript.CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set F = FSO.GetFile(Wscript.ScriptFullName)
path = FSO.GetParentFolderName(F)
objShell.Run(CHR(34) & "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "" -ExecutionPolicy Bypass & ""'" & path & "\Ps1File.ps1'" & CHR(34)), 0, True
at the console prompt type:
mstsc /v:SERVERNAME
Try using this command: mstsc /v:<server>
additionally you can check the following link for further reference:
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/mstsc
If you are working with remote hosts in domain, u can use this command:
Enter-PSSession -ComputerName host1 -Credential Username
If not, u should execute some steps.
This link has many other options:
http://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/

Copy/transfer file using PowerShell 2.0

I'm trying to create a PowerShell script to copy a file from my local computer to remote computer using its IP address.
I tested my client-server connection by using this command:
Invoke Command -ComputerName <IP Address> -ScriptBlock {ipconfig} -Credential $credential
(where $credential had been entered just before this command).
I tried using the Copy-Item and Robocopy commands but I'm not clear if it will even take my credentials and then let me copy a file from a local to a remote machine. To be specific, would these even support local to remote file transfer?
A lot of times I faced errors like:
Bad username and password, source path does not exist or destination path does not exist. But I still wanted to be sure if I was on right track and using the right commands to implement what I want to or if there is something else which I should consider using. How can I fix this problem?
It looks like you're trying to copy a file using PowerShell remoting. As posted in other answers, it would be simpler to use Copy-Item and/or Robocopy to copy from the source to a share on the destination computer.
If you want to copy the file using PowerShell remoting, you can slurp the file into a variable and use it in the remote script block. Something like:
$contents = [IO.File]::ReadAllBytes( $localPath )
Invoke-Command -ComputerName <IP Address> `
-Credential $credential `
-ScriptBlock { [IO.File]::WriteAllBytes( 'C:\remotepath', $using:contents ) }
Of course, if the file you're reading is really big, this could cause the remote connection to run out of memory (by default, PowerShell limits remote connections to around 128MB).
If you're stuck using PowerShell 2, you'll need to pass the bytes as a script block parameter:
$contents = [IO.File]::ReadAllBytes( $localPath )
Invoke-Command -ComputerName <IP Address> `
-Credential $credential `
-ScriptBlock {
param(
[byte[]]
$Contents
)
[IO.File]::WriteAllBytes( 'C:\remotepath', $Contents)
} `
-ArgumentList #( ,$contents )
And yes, you must wrap $contents in an array when passing it as the value to the -ArgumentList parameter and it must be prefixed with the comma operator ,, otherwise your remote script block will only receive the first byte.
One of the nice things about PowerShell is (unlike DOS) it support UNC paths. So you can literary just do:
Copy-Item -Path <local file path> -Destination \\<server IP>\<share>\<path>
Of course your account will need to have access to that location. If you need to enter alternate credentials you can pre-authenticate using net use \\<server IP>\<share> /user:[<domain>\]<user> <password>