Powershell - automatically add password into copy-item code - powershell

Good day all,
I am running a line of code to download agent logs from multiple servers remotely but I am running into a delay with the current line of code I am working with.
copy-item -path C:\Agent.txt -destination c:\Local\ -fromSession (new-PSSession SERVERNAME -credential DOMAIN\USERNAME -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck))
This will prompt for credentials with the DOMAIN\USERNAME already filled in. What I am hoping to do is for it to begin the download immediately without me having to type in a password for each one.
TIA

This is an ideal place to use variables. You are being prompted each time because you instructed it to do so. If you break it up and store the credentials in a variable, then you won't keep getting prompted.
$session = new-PSSession SERVERNAME -credential DOMAIN\USERNAME -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck)
copy-item -path C:\Agent.txt -destination c:\Local\ -fromSession $session
You may also consider splatting to make the code easier to read and maintain. This may not be the best demonstration, however I thought it was worth mentioning.
$sessopt = #{
ComputerName = 'SERVERNAME'
Credential = 'DOMAIN\USERNAME'
UseSSL = $true
SessionOption = New-PSSessionOption -SkipCACheck
}
$session = New-PSSession #sessopt
$copyopt = #{
Path = 'C:\Agent.txt'
Destination = 'C:\Local\'
FromSession = $session
}
Copy-Item #copyopt

Related

How can I connect to Exchange online (connect-exopssession) with credentials and no form?

I've tried a couple of variants of this (all 3 shown below). With this code, if I specify a value for -UserPrincipalName a form will pop up quickly and disappear, fast enough to where only the form borders are rendered. If I do not specify a value for -UserPrincipalName, that same form opens and asks for me to sign in with my email address. The third option I tried was with -Credential and a credential object, I get the error:
"New-ExoPSSession : missing_federation_metadata_url: Federation Metadata Url is missing for federated user. This user type is
unsupported." .
My end goal here is to authenticate without the form popping up so I can run some code with a scheduled task, which right now will not work because of the form and interactive mode. I can use creds, NO MFA and need to supress this form
somehow.
How can I connect to Exchange Online without this form appearing? Is there a way to use New-PSsession or Import-PSsession, or to wrap the New-ExoPSSession in something that prevents it from opening a form?
(Also, we need an "exchange-online" tag added, I don't have enough reputation to do so)
[string] $ConnectionUri = "https://outlook.office365.com/PowerShell-LiveId"
[string] $AzureADAuthorizationEndpointUri = 'https://login.windows.net/common'
[System.Management.Automation.Remoting.PSSessionOption] $PSSessionOption = $null
[switch] $BypassMailboxAnchoring = $false
[string] $DelegatedOrganization = ''
$PSSession = New-ExoPSSession -UserPrincipalName "xxx#xxx.xxx" -ConnectionUri $ConnectionUri -AzureADAuthorizationEndpointUri $AzureADAuthorizationEndpointUri -PSSessionOption $PSSessionOption -BypassMailboxAnchoring:$BypassMailboxAnchoring -DelegatedOrg $DelegatedOrganization
$PSSession = New-ExoPSSession -ConnectionUri $ConnectionUri -AzureADAuthorizationEndpointUri $AzureADAuthorizationEndpointUri -PSSessionOption $PSSessionOption -BypassMailboxAnchoring:$BypassMailboxAnchoring -DelegatedOrg $DelegatedOrganization
$user = "xxx#xxx.xxx";
$password = ConvertTo-SecureString "xxxx" -AsPlainText -Force;
$creds = New-Object System.Management.Automation.PSCredential -ArgumentList ($user, $password)
$PSSession = New-ExoPSSession -UserPrincipalName "xxx#xxx.xxx" -ConnectionUri $ConnectionUri -AzureADAuthorizationEndpointUri $AzureADAuthorizationEndpointUri -Credential $creds -PSSessionOption $PSSessionOption -BypassMailboxAnchoring:$BypassMailboxAnchoring -DelegatedOrg $DelegatedOrganization

Enter-Pssession not working

I have to machines in same network one with windows7 and another win windows server 2012.I tried Enter-PSsession on windows7 machine from server2012 machine...
$ComputerName = "windows7-PC"
$username="administrator"
$password="password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cr = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$Session = New-PSSession -ComputerName $ComputerName -Credential $cr
Invoke-Command -Session $Session -ScriptBlock { echo '1' }
On doing same,i got an error
New-PSSession : [windows7-PC] Connecting to remote server windows7-PC failed with the following error message : Access is denied.
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
using same script i m able to execute 'echo 1' from windows7-pc to server2012-pc but not from server2012-pc to windows7-pc.
You need to add the remote server in trusted domain.
Please follow below article:
https://technet.microsoft.com/en-us/magazine/ff700227.aspx
This will surely help you.

Variable values to pass from local computer to remote in Pssession

I have a powershell script. Executing this will create a session with remote computer and execute some scriptblock inside remote computer. After that execution I need to send a mail.
So, I get the arguments required (like from, to, subject, body, smtp server, credentials) etc locally as shown below:
$param = #{
SmtpServer = 'SMTPServer'
Port = 587
UseSsl = $true
Credential = $crede
From = 'server#domain.in'
To = 'userv#domain.in'
Subject = 'Hi'
Body = "Hello"
}
$crede has value (username explicitly given, password reading from a text file).
And I call that param as shown below:
Send-MailMessage $using:param
This is inside an Invoke-Command.
But when I run this program it asks me for the mail message details like from, to, smtp server etc.. Please note that these values are given on $param locally. I guess $param values are not being passed to the remote session.
Can someone please support me. Any help would be really appreciated.
I just had a similar issue.
$processName = myProcess.exe
$session = New-PSSession -ComputerName $anycomputer -Credential $credentials
# powershell syntax requires -Scriptblock and { on this line
Invoke-Command -Session $session -ScriptBlock {
param([string] $processName)
Get-Process -Name $processName
} -Args $processName
Remove-PSSession $session
$processName = myProcess.exe
$session = New-PSSession -ComputerName $anycomputer -Credential $credentials
Invoke-Command -Session $session {Get-Process -Name $using:processName}

Modifying Existing CSV file in Powershell

I have a script that I am setting up to do some migration of users' Exchange mailboxes into .pst file. The idea was that I would have a CSV file that I could put users' names on and then when the script kicked off nightly it would open the CSV file and find users that have been added, perform the requested actions on those users accounts (export, move set permissions etc) and then write back to the CSV file Marking those users as completed and writing the date on which they were completed. Here is what I have so far.
$InPstPath = '\\server1\PST_Store\'
$OutPstPath = '\\server2\PST_Store\'
$User = Get-Content $OutPstPath'login.txt'
$PWord = cat $OutPstPath'pass.txt' | convertto-securestring
$Credentials = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
$PSSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Server1/powershell -Credential $Credentials
Import-PSSession $PSSession
$In_List = Invoke-Command {Import-Csv "\\Server1\PST_Store\Admin\To_Be_Exported.csv"} -computername Server1 -Credential $Credentials
foreach ($objUser in $In_List) {
if ($objUser.Completed -ne "Yes") {
$TargetUser = $objUser.name
$ShortDate = (Get-Date).toshortdatestring()
New-MailboxExportRequest -Mailbox $TargetUser -Filepath "$InPstPath$TargetUser.pst"
$objUser.Completed = "Yes"
$objUser.Date = $ShortDate
}
}
Remove-PSSession -Session (Get-PSSession)
I can't figure out a decent way to write back the $objUser.Completed and $objUser.Date values to the CSV.
Firstly, it's obvious but let me state it anyway. The very first time you run this script, $objUser.name, $objUser.Completed and $objUser.Date will not exist; So, the line
$TargetUser=$objUser.name
will not work, unless you actually have the structure in place in that csv (i.e. have the headers name,completed,date).
Now assuming you got that part done, all you have to do is to create an object that captures the state in an object and then write that back.
$Processed = foreach ($objUser in $In_List) {
if ($objUser.Completed -ne "Yes") {
$TargetUser = $objUser.name
$ShortDate = (Get-Date).toshortdatestring()
New-MailboxExportRequest -Mailbox $TargetUser -Filepath "$InPstPath$TargetUser.pst"
[PSCustomObject]#{Name=$objUser.name;Completed="Yes";Date=$ShortDate}
}
} else {
[PSCustomObject]#{Name=$objUser.name;Completed="No";Date=$null}
}
## export to a temp file
$Processed | export-csv -Path $env:TEMP\processed.csv
## You should probably check to see if original file was modified since you started working on it
# and copy over if not
Copy-Item $env:TEMP\processed.csv $OutPstPath'login.txt' -force

rdesktop shell escaping issue

I'm trying to send this:
Get-WmiObject Win32_PNPEntity |Where{$_.DeviceID.StartsWith("PCI\VEN_10DE") -or $_.DeviceID.StartsWith("PCI\VEN_1002")}
over rdesktop like:
rdesktop -a8 209.** -u ** -p ** -s "cmd.exe /K powershell.exe Get-WmiObject Win32_PNPEntity |Where{\$_.DeviceID.StartsWith("PCI\VEN_10DE") -or $_.DeviceID.StartsWith("PCI\VEN_1002")}"
But windows' shell says:
'Where{$_.DeviceID.StartsWith' is not recognized as an internal or externa....
What am I doing wrong?
why not using powershell wmi remoting?
$cred = get-credential
Get-WmiObject Win32_PNPEntity -computerName MyRemoteComputerName - credential $cred |Where{$_.DeviceID.StartsWith("PCI\VEN_10DE") -or $_.DeviceID.StartsWith("PCI\VEN_1002")}
-credential are only needed if the actual user running powershell isn't administrator of remote machine.
Hi I needed to do some thing like this once so i wrote some code that can send any ps code to a remote computes and display the results in the ps window on your pc.
Just remember to enable powershell remoting on both pc's.
function remote-pscode ($ServerName,$UserName,$password,$PSCode)
{
$global:RemoteCode = $args[0]
Write-Host $RemoteCode
$conprops = (Get-Host).UI.RawUI
$buffsize = $conprops.BufferSize
$buffsize.Height = 800
$conprops.BufferSize= $buffsize
# Set the user name you would like to use for the connection
$global:RemoteUserName = $UserName
$global:RemoteServerName = $ServerName
# Set the password you would like to use for the connection
# Check to see if you have a file on you drive c:\cred.txt with a password to use in it,if you don't it will create one
# for you and ask you for the password you would like to use
$global:RemotePassword = convertto-securestring $password -AsPlainText -Force
$global:credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $RemoteUserName,$RemotePassword
#Create a connection to the remote computer , put a list of IPAddresses or Computer Names.
$global:session = new-PSSession -ComputerName $RemoteServerName -Credential $credentials
$ScriptBlock = $executioncontext.invokecommand.NewScriptBlock($RemoteCode)
invoke-command -Session $session -ScriptBlock $ScriptBlock
#Close the sessions that where created
$global:closesession = Get-PSSession
Remove-PSSession -Session $closesession
}
remote-pscode -ServerName "NameOfRemotePC" -UserName "UserName" -password "password" -PSCode "any powershell code you want to send to the remote pc"
Several things here: put your PS commands in a script block (or a script). Also, why don't you simply use wmic.exe ?