AUDIT_FAILURE when running Get-PSDrive from remote system - powershell

We run a script to connect to a remote server over a VPN and copy a file.
First we created a password file:
$credential = Get-Credential
$credential.Password | ConvertFrom-SecureString | Set-Content C:\Scripts\password.txt
And then we use that password file to map a drive with Get-PSDrive and copy a file:
Get-PSDrive Q | Remove-PSDrive
$password = Get-Content C:\Scripts\password.txt | ConvertTo-SecureString 
$credential = New-Object System.Management.Automation.PsCredential("DOM\user", $password)
New-PSDrive -name "Q" -PSProvider FileSystem -Root \\192.168.1.100\Test -Credential $credential -Persist
Copy Q:\*.* C:\Scripts
This works, but we see AUDIT_FAILUREs in the event log which our monitoring system is flagging. It tries to use local credentials from where the script runs, which aren't valid and therefore causes the AUDIT_FAILURE.
Cannot see why we get this issue.

Related

Connecting to remote machine from PowerShell

I am trying to copy files from one domain to a remote machine in another domain. I want to use constant credentials. No matter what I tried, it doesn't work. I can ping to the remote machine only via IP and not by hostname.
$labname='L1681'
$remoteComputer = "10.32.22.157"
$username = "$labname\Administrator"
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$session = New-PSSession -ComputerName $remoteComputer -Credential $creds
$Source = "\\...\folder"
$Destination = "\\$remoteComputer\c$\Users\Administrator\Desktop"
New-Item -ItemType Directory -Path $Destination -Force
Copy-Item -Path $Source -Recurse -Destination $Destination -Force -ToSession $session
I tried to replace the $labname with $remoteComputer. Each time I get a different error:
Enter-PSSession : Connecting to remote server 10.32.22.157 failed with the following error message : The WinRM client cannot process the request. Default authentication may be used with an IP address under the following conditions:
the transport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more
information on how to set TrustedHosts run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName $remoteComputer -Credential $creds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (10.32.22.157:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
I hope someone can help me with that, is there a way to know when the copy if finished, once it works? Also, how can I run a .bat file in a remote machine?
You can try this script which establishes a remote connection to a VM and copy a text file from the Local directory to that Remote VM.
#Provide the Remote VM Username and Password
$myPwd="Your VM Password"
$username="VM Username"
$password = ConvertTo-SecureString $myPwd -AsPlainText -Force
$credentials= New-Object System.Management.Automation.PSCredential ($username, $password)
#Create a remote session to that VM
$Session = New-PSSession -ComputerName FQDN/IP -Credential $credentials
#Check the content to the Local File that will be copied to Remote
Get-Content -Path "C:\LocalFolder\File.txt"
#Create a folder named *RemoteFolder* then copy the local file to that Folder
Invoke-Command -Session $Session -ScriptBlock {cd C:\; mkdir RemoteFolder}
Copy-Item –Path "C:\LocalFolder\File.txt" –Destination "C:\RemoteFolder\" –ToSession $Session
#Check the content of the copied file
Invoke-Command -ScriptBlock { Get-Content -Path "C:\RemoteFolder\File.txt" } -Session $Session
The screenshot of the output after running this script:

Powershell Remote Copy fails, locally it works

We have logfile on a server A in a different location (no UNC Path access) and we wish to copy the file to server B. This successfully works with Copy-Item -FromSession (run on Server B) as long as the file is closed. So we can successfully copy the previous day's logs but not today's.
$cred = Get-OurUserCredentials
$sess = New-PSSession -ComputerName $ServerA -Credential $cred -Authentication Negotiate
$LogFile = "D:\log\tomcat\access.20180227.log"
Copy-Item -FromSession $sess $LogFile "D:\logs\tomcat\" -Force
However, we can locally copy the active log of today if we run Copy-Item locally on server A. It's only Copy-Item -FromSession on server B which fails with:
Copy-Item : The process cannot access the file 'D:\log\tomcat\access.20180227.log' because it is being used by another process.
At line:11 char:2
As a workaround we could create a local task on server A to create a local copy but why is this necessary?
Why does Copy-Item behave differently when run remotely and can we "fix" it's behaviour so it copies the log remotely as it would locally.
A version of the answer proposed in the OP but avoiding the need for a scheduled task.
$cred = Get-OurUserCredentials
$sess = New-PSSession -ComputerName $ServerA -Credential $cred -Authentication Negotiate
#ScriptBlock to copy file locally
$SB =
{
#Create variables on the remote machine avoid havin gto pass to scriptblock
$LogFile = "D:\log\tomcat\access.20180227.log"
$TempDes = "temporarylocationhere"
Copy-Item -Path $LogFile -Destination $Des
}
#optional scriptblock to clean up
$SB2 =
{
Remove-Item -Path $TempDes -force
}
#Run the copy file scriptblock
Invoke-Command -Session $sess -ScriptBlock $SB
#Copy file
Copy-Item -FromSession $sess $TempDes "D:\logs\tomcat\" -Force #"
#Run clean up scriptblock
Invoke-Command -Session $sess -ScriptBlock $SB2
Have you considered using a PSDrive to map the remote location and then copy the file to or from that drive?
The New-PSDrive cmdlet creates temporary and persistent drives that
are mapped to or associated with a location in a data store, such as a
network drive, a directory on the local computer, or a registry key,
and persistent Windows mapped network drives that are associated with
a file system location on a remote computer.
Example using your code:
# Change the ServerNameToCopyTo below
New-PSDrive -Name "Remote" -PSProvider "FileSystem" -Root "\\ServerNameToCopyTo\log\tomcat\"
$LogFile = "D:\log\tomcat\access.20180227.log"
Copy-Item $LogFile "Remote:\" -Force

GCE Windows startup scripts & naming

Linux admin pulling out what hair I have left trying to figure out startup scripts for Windows on GCE.
The way I've approached it is the following;
Create a "runonce" script by editing the registry on the "master" image.
Said script does the following;
-
Does a reverse DNS lookup of it's own IP to get the hostname DNS thinks it is and then sets the local hostname to that
Joins the domain
Adds a domain user as autologin (I need this for various reasons)
I GCESysprep the machine
Take an image of the machine after sysprep and make a group template from that
My main issue I'm having is that it's not working at all :) The machines come up, run the script and reboot but god knows what state they're in after they come back, I can't login, reset the password/do anything.
I think ideally what I'd like to do is figure out the best way of doing this, do I host the script in GCE Storage and mark it a startup script in the GCE Console opposed to the registry setting? Is there a better way of renaming the machines?
Here's the script if you're interested;
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
$ipAddresses = (get-netadapter | get-netipaddress | ? addressfamily -
eq 'IPv4').ipaddress
# Filter out any 192.168 172. 10. IP addresses
$ipAddress = $ipAddresses -like "123*"
# Retrieve the hostname from the ??? DNS Server
$fqdn = (nslookup $ipAddresses | sls name | select -last
1).toString().split(":")[1].trim()
# We only need the hostname without the domain info so split it up
$fqdn_items = $fqdn.split(".")
$newComputerName = $fqdn_items[0]
Write-Host "New Computer Name: $newComputerName"
# Get a WMI object representing the current computer
$currentComputer = Get-WmiObject Win32_ComputerSystem
Write-Host "Attempting to change computer name to $newComputerName"
# Set the Computer Name to the hostname found via DNS Lookup to DNS
Server
# This can only be performed before joining the domain otherwise you
get return code 1326
$currentComputer.Rename($newComputerName)
#SET CREDENTIALS
$domain = “mydomain”
$password = “password” | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\joinuser”
$credential = New-Object
System.Management.Automation.PSCredential($username,$password)
# RENAME THE COMPUTER
Rename-Computer -ComputerName (hostname) -NewName $newComputerName -
LocalCredential $credentiallocal
sleep 100
# JOIN THE DOMAIN
Add-Computer -DomainName $domain -Credential $credential -force
# CONFIGURE AUTOLOGIN
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon' -Name AutoAdminLogon -Value 1
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon' -Name DefaultUserName -Value
“mydomain\dr-worker"
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows
NT\CurrentVersion\Winlogon' -Name DefaultPassword -Value mypassword
restart

using new-psdrive name as source variable for msdeploy source parameter does not work

// Create a new powershell drive
$psw = ConvertTo-SecureString %deployment.password% -AsPlainText -force
$cred = new-object -TypeName System.Management.Automation.PSCredential -ArgumentList "MyUser, $psw
New-PSDrive -Credential $cred -Name ImportFolder -PSProvider FileSystem -Root \\MyShare\Exchange\MyFolder
// Create a full source path
$sourcePath = ImportFolder:\$versionPath\audio
// Deploy with msdeploy and the $sourcePath
$path = "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe";
$verb = "-verb:sync";
$src = "-source:contentPath=`"$sourcePath`"";
$dest = "-dest:contentPath=%TargetIISPath%,wmsvc='%Computername%:%deployment.iis.port%/msdeploy.axd',username=%system.Username%,password=%system.Password%";
Invoke-Expression "&'$path' --% $verb $src $dest -verbose -allowUntrusted";
Remove-PSDrive ImportFolder
I get the error:
The term 'ImportFolder:\$versionPath\audio' is not recognized as the name of a
[21:07:32][Step 6/7] cmdlet, function, script file, or operable program. Check the spelling of the
[21:07:32][Step 6/7] name, or if a path was included, verify that the path is correct and try
[21:07:32][Step 6/7] again.At
The problem is that msdeploy assumes the sourcePath ImportFolder is literally named "ImportFolder" but actually it is a powershell drive with a mapped path...
How can I fix that?
I do NOT want to use "net use X:\ path" because its buggy in my environment.
This might be a bit old, but you can just use a Name with a letter for your PSDrive, and then you can use that drive letter with msdeploy
New-PSDrive -Credential $cred -Name "X" -PSProvider FileSystem -Root \\MyShare\Exchange\MyFolder
$sourcePath = "X:\$versionPath\audio"

PowerShell map persistent sharepoint path

I'm trying to map the path to a SharePoint document library in a persistent way. It's strange that this works fine:
$Sharepoint = '\\domain.net\stuff\Documents\Folders - Permission matrix'
New-PSDrive -Name P -Root $Sharepoint -PSProvider FileSystem -Credential $Credentials
But this doesn't work:
New-PSDrive -Persist -Name P -Root $Sharepoint -PSProvider FileSystem -Credential $Credentials
New-PSDrive : The network resource type is not correct
At line:1 char:1
+ New-PSDrive -Persist -Name P -Root $Sharepoint -PSProvider FileSystem -Credentia ...
The commands are both using the same PSProvider but one is persistent and the other one not. How can I have this persistent without reverting to net use?
I ran into this problem a few weeks back in a script which mysteriously stopped worked whilst I was developing it, seems to be a Windows error 66 rather than Powershell as explained here
Here is an alternative to net use which uses credentials
# map drive using credentials
(New-Object -ComObject WScript.Network).MapNetworkDrive("$LocalDrive","\\$computer\$drive",$false,$($credentials.username),$($credentials.GetNetworkCredential().password))
I tend to use PSDrive like this
# discover and delete
if (Get-PSDrive -Name Results -ErrorAction SilentlyContinue) { Remove-PSDrive -Name Results -Scope Global | Out-Null }
# create using credentials
if ((New-PSDrive -Name Results -PSProvider FileSystem -Root "\\server\share" -Credential $Credentials -Scope Global -ErrorAction SilentlyContinue) -eq $null) { $WSHShell.popup(“You do not have access to the results repository“,0,””,0) | Out-Null }
# call from a separate function
(Get-PSDrive -Name Results).root
It might just be that a reboot will solve the problem because I cannot recreate the issue today.
I had a similar issue, turns out Windows 2016 and 2019 needs WEBDav Redirection installed.
I was getting error 53, when trying to map a SharePoint library.