How to change this script so netrwork drive is still aviable after machine reboot?
$User = "user"
$PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$net = $(New-Object -ComObject WScript.Network)
$net.MapNetworkDrive("r:", "\\name\othername")
Powershells way:
New-PSDrive -Name "R" -PSProvider FileSystem -Root "\\name\othername" -persist:$true -Scope Global
Use:
net use r: \\name\othername
Related
I am writing a powershell script that copies a .jar file from a server to a remote VM. When it gets to the Copy-Item command, it fails with this error:
Copy-Item : The user name or password is incorrect.
+ Copy-Item -Path $source -Destination '\\consolidate\c$ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Comma
nds.CopyItemCommand
I have tried adding a -Credentials argument to the Copy-Item command. That gives me this error:
The FileSystem provider supports credentials only on the New-PSDrive cmdlet.
Perform the operation again without specifying credentials.
At [file path]
+ Copy-Item -Path $source -Destination '\\consolidate\c$ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported
Here is the code around the line in question:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
Invoke-Command -ComputerName "consolidate" -Credential $credentials -ScriptBlock {
New-PSDrive -Name "X" -PSProvider FileSystem -Root "C:\" -Credential $Using:credentials
}
Copy-Item -Path $calcEngineJarPath -Destination '\\consolidate\c$'
...
Remove-PSDrive X
You'd want to create a new PSDrive on your local machine that maps the network path to a drive letter:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
# Create mapped network drive
New-PSDrive -Name "X" -PSProvider FileSystem -Root "\\consolidate\c$\" -Credential $credentials
# Copy to mapped network drive
Copy-Item -Path $calcEngineJarPath -Destination X:\
Alternatively, use Copy-Item's -ToSession parameter:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
# Create a new PSRemoting session on the target machine using the credentials
$session = New-PSSession -ComputerName consolidate -Credentials $credentials
# Copy file to remote session drive
Copy-Item -Path $calcEngineJarPath -Destination C:\ -ToSession $session
I'm automating the process of creating LocalUsers on Windows systems. So far I used the Microsoft docs on New-LocalUser which has worked fine to create the account, this is my code so far:
function New-AdminUser {
param(
[Parameter(Position=0)]
[string] $UNameLocal,
[Parameter(Position=1)]
[string] $UDescription,
[Parameter(Position=2)]
[System.Security.SecureString] $Password
)
New-LocalUser -Name $UNameLocal -Description $UDescription -Password $Password -AccountNeverExpires -Confirm
Add-LocalGroupMember -Group "Administrators" -Member $UNameLocal
}
But this command does not actually generate the homedirectory in C:\Users\username.
I can create this by manually logging into the created user, but I want to automate this in Powershell. I couldn't find anything in the LocalAccounts module.
Is there any way to automate local account setup in Windows 10 using Powershell, without having to manually log in to a new account?
If you start a process (cmd /c) as the created user, it will create his profile. Add this to your function:
$Cred = New-Object System.Management.Automation.PSCredential ("$UNameLocal", $Password)
Start-Process "cmd.exe" -Credential $Cred -ArgumentList "/C" -LoadUserProfile
Here is the code:
param([Parameter(Mandatory=$true)][String]$samAccountName)
$fullPath = "\\srv2012r2\Users\{0}" -f $samAccountName
$driveLetter = "Z:"
$User = Get-ADUser -Identity $samAccountName
if($User -ne $Null) {
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath -ea Stop
$homeShare = New-Item -path $fullPath -ItemType Directory -force -ea Stop
$acl = Get-Acl $homeShare
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ea Stop
Write-Host ("HomeDirectory created at {0}" -f $fullPath)
}
and here is the reference:
https://activedirectoryfaq.com/2017/09/powershell-create-home-directory-grant-permissions/
Basically I want to switch user in powershell in the same window (dont want to open a new one).
$username = "xxxxx"
$password = ConvertTo-SecureString "xxxxx" -AsPlainText -Force
$creds = New-Objet System.Management.Automation.PSCredential $username,$password
Start-Process powershell.exe -NoNewWindow -Credential $creds
But instead of launching powershell in same window it launches it in a new window which doesnt even work I cant type anything into its just a blinking cursor.
First things first, try to describe what you need to do in detail since the approach you're using might be misguided. Are you just trying to run commands as a different user within a script? If so, use the methods described here : https://www.itdroplets.com/run-a-command-as-a-different-user-in-powershell/
I particularly like the start-job method which I use sometimes, example:
#Shows who is the current user
whoami
""
$username = "DOMAIN\USER"
$password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential $username,$password
$GetProcessJob = Start-Job -ScriptBlock {
#Shows who is the current user, in this case it's the user you provided credentials for. Everything in this scriptblock will run in his context.
whoami
} -Credential $Credential
#Wait until the job is completed
Wait-Job $GetProcessJob | Out-Null
#Get the Job results
$GetProcessResult = Receive-Job -Job $GetProcessJob
#Print the Job results
$GetProcessResult
If you truly just want to just launch another powershell.exe process as another user,
the only way I know of would be to simply start the new process and exit the first one after that command, this way you have only the new window running as the user provided.
$username = "DOMAIN\USER"
$password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential $username,$password
Start-Process powershell.exe -Credential $creds ;Exit
I'm trying to do the following script:
$EP = ExecutionPolicy
$Username = 'backup'
$Password = Get-Content 'C:\SecureString.txt' | ConvertTo-SecureString
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $Password
Import-Module VMware.DeployAutomation, ConfluencePS
if ($EP -eq 'Unrestricted') {
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force
}
Set-ConfluenceInfo -BaseURI 'https://confluence.my.company' -PromptCredentials -Credential $Cred
Get-ConfluencePage
The problem is that even passing the variable with user and password it's still prompting me the authentication window and i didn't find any way to disable or avoid it.
Am I doing in the correct way?
thanks in advance.
Since i was using both -PromptCredentials and -Credential the windows was prompted regardless it already had user and password, so the solution was about to remove -PromtCredentials command.
Set-ConfluenceInfo -BaseURI 'https://confluence.my.company' -Credential $Cred
I want to copy a file from the remote server to local, and my code is
Make sure the xxx.xxx.x.xxx's connection
>
Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString | Out-File"C:\Users\chrishchang\Desktop\powershell/remote-password.txt"
$user = get-content C:\Users\chrishchang\Desktop\powershell/remote-user.txt
$pass = get-content C:\Users\chrishchang\Desktop\powershell/remote-password.txt |
ConvertTo-securestring
&myCred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$pass
$session = new-pssession -computername name -credential $myCred
Invoke-Command -ComputerName xxx.xxx.x.xxx -ScriptBlock { ipconfig /all } -credential $myCred
create the new file
>
$command={New-Item c:\scripts\new_file.txt -type file -force -value "This is text added to the file"}
Invoke-Command -session $session -scriptblock $command
copy the file from xxx.xxx.x.xxx to local
>
$command={Copy-Item -FromSession $session -Path "c:\scripts\new_file.txt" -Destination "C:\Users\chrishchang\desktop\"}
Invoke-Command -session $session -scriptblock $command
The error result..
enter image description here
Please give me some suggestion, I have suffered from it for a long time.
The last step (3) should be:
Copy-Item -FromSession $session -Path "c:\scripts\new_file.txt" -Destination "C:\Users\chrishchang\desktop"
Don't use Invoke-Command as the Copy-Item already uses the session.