Powershell persistent mapped drive won't save credentials for next logon - powershell

So I have this powershell (or vbs or batch) script I'm trying to write. All it needs to do is a map a network drive persistently using alternate credentials. For some reason, it seems like the credentials aren't persisting. It maps fine initially then on login the drive will have a red X and when trying to open it I'll get prompted for the password.
When running powershell as the admin, upon re-logon, the drive isn't even shown anymore. I'm guessing because of a scope issue, but I thought the global flag was supposed to take care of that?
I've also tried the "net use" method and the "Wscript.Network" method from within powershell... same results.
I'm new-ish to windows scripting so it's probably something really dumb. Here's the essentials of the script I'm using. I'm pasting it directly into the powershell window. Where have I gone astray?
$user = "USERNAME"
$pass = "PASSWORD"
$cur_share = "\\192.168.1.100\websites"
$drive = "X"
$PWord = ConvertTo-SecureString -String $pass -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $PWord
New-PSDrive -Name $drive -PSProvider "FileSystem" -Root $cur_share -Scope "Global" -Persist -Credential $Credential

You are seeing this behavior because you are using alternate credentials. If I use your code with my own credentials the drive persists even across reboots but if I use alternate credentials it does not. This is apparently as designed.
Relevant details from the cmdlet help:
Mapped network drives are specific to a user account. Mapped network
drives that you create in sessions that are started by using the Run
as administrator option or by using the credential of another user are
not visible in a session that was started without explicit
credentials, or by using the credentials of the current user.
Reference:
https://technet.microsoft.com/en-us/library/hh849829.aspx?f=255&MSPPError=-2147217396

Thanks Jon. Just as you post that I found a workable solution. The key is to store the credential in the manage before using the network path.
$result = cmdkey /add: "192.168.1.100" /user: "USERNAME" /pass: "PASSWORD"
That stores the credentials persistenty. Then mapping the drives persistently works with no password prompt.

Related

Error when global variable in Orchestrator 2012 is encrypted

I'm trying to use some credentials so I can connect to MicrosoftTeams using powershell with orchestrator. I need a username and its password. The password is stored as a global variable, encrypted. When I try to connect to MicrosoftTeams it says that the password is incorrent. However, when I put the password hard coded there is no problem, and I can connect to Microsoft Teams.
Here is my code:
$Pass = ConvertTo-SecureString '{password}' -AsPlainText -Force
$admin ="admin#admin.com"
$cred = new-object -typename System.Management.Automation.PSCredential -argumentList $admin, $password
connect-MicrosoftTeams -credential $cred
Has someone had the same issue?
I think my problem was because I was using a PowerShell Script activity. It turns out that this activity can't read encrypted variables. To solve this problem I just enctypted the password and stored it in my C: drive, then I just got the content from that file. If someone wants the code for that, please ask.

Create PSCredential from AzureAD User

I don't know why I can't figure this out, this can't be as hard as I'm making it. I'm trying to create a powershell script that will elevate itself using explicit credentials from AzureAD. I create a PSCredential object with:
$ss = ConvertTo-SecureString "p#ssw0rd" -AsPlainText -Force
$cred = New-Object PSCredential -ArgumentList 'username#domain.com', $ss
Start-Process PowerShell -Credential $cred "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`""
exit;
When I execute this I get Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
I know the username and password are correct but I am guessing that it has to do with the fact that this is an AzureAD user? Do I have to format the AzureAD username differently? I've tried reformatting it every way I can think of. I've tried using Connect-AzureAD and using Get-AzureADUser to try to see if I could use some property of that to sign in but I'm coming up empty.
Is this even possible?
With Start-Process you must specify username in format "DOMAIN\user". I am not sure where from this limitation is coming.
Is the domain that the azure ad user account you are trying to run the command as accessible to the domain that your machine is connected to? Without more information, I can only speculate that powershell is throwing the error because it does not recognize the user or the domain the user is a member of.

Enter-PSSession Id with credentials

I'm trying to enter a specific session on a remote machine which has credentials.
I have already setup trusted hosts etc.. and have successfully run commands on new virtual sessions.
I would like to enter the session by providing a session ID.
I have seen documentation for each seperate ways but I'm not sure how to combine them, can someone help?
This is what I would imagine it would look like
$username = "exampleUsername"
$password = ConvertTo-SecureString "examplePassword" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList($username, $password)
$serverNameOrIp = "exampleIp"
$sessionId = 2
Enter-PSSession -Id $sessionId -ComputerName $serverNameOrIp -Credential $cred
However I'm getting very clear invalid argument exceptions which makes sense since the documentation doesn't say anything about this combination:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pssession?view=powershell-7
Is there a way to do this? I may be missing something obvious or looking in the wrong place. Many thanks in advance
(for more info)
EDIT:
I am trying to connect to the current interactive user session and run some commands for the user to see. The user is permanently logged in/already logged in and I have their session ID. I just need to use it and connect to it however there are still credentials to use for the machine - I'm unsure how to combine these two.

How to store local administrator username and password in powershell script

I am creating a PowerShell script that a user can just run to edit an entry in registry. My problem is that I cannot figure out how to store local admin username and password in the same script so that the user can just double click the script and run it without having to enter username and password manually.
Here is my code:
$username = "testpc\administrator"
$pasword = get-content C:\Users\test1\documents\testpassword.txt
$credential = new-object -typename system.management.automation.pscredential -argumentlist $username, $password
This does not work at all. Please let me know what I am doing wrong here.
Usually I'd ask for an error, but in this case I'll advise different, just because your approach isn't acceptable.
Don't store passwords unencrpted in script. Never.
Don't store passwords encrypted in scripts, which are meant to be read by someone else, especially not a user with less privileges. Never!
Go, figure other ways to solve your problem. Always!
In this case I see two solutions with the given information:
change the ACL for the registry key that need to be changed by the user
Create a scheduled task which runs as SYSTEM. Make sure the user cannot edit the script.
Actually #vrdse is right.
you can create the script with the KEY as parameter and:
create a scheduled job with the credentials of your user and add the script as task.
give the user the right to execute the job but NOT to edit or to delete
give a shortcut to the scheduled job (or a runner script) to the user and make a how-to document to show him,/her how the parameter should be used.
I use clear text passwords as temporary testing stuff to make sure users CANNOT use my script (so it is exactly the opposite of your action).
You can capture credential during execution:
$cred = get-gredential -message 'This script needs a real admin user'
Enter-PSSession -Credential $cred -ComputerName 127.0.0.127
You can build a credential (do not store privileged user data):
$user = 'SuchAGreatDomainName\IAmLowPrivilegedUserName'
$Password = 'SuperSecretPassEverybodyKnows'
$secpassword = ConvertTo-SecureString $Password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpassword)
Invoke-RestMethod -Uri $Uri -Credential $Credential

Looking to map an Azure Fileshare as a mapped network drive on an Azure Windows VM via another machine/Custom Script Execution

I'm attempting to provision a Windows VM and I need to map some Azure fileshares to drives for the VM user that will be interacting with the VM.
I've been trying to make "az vm extension set"/Custom Script Execution work for me by calling some PowerShell scripts to setup the mapping to the fileshare, but since the process runs as NT AUTHORITY\SYSTEM, the mappings aren't working, obviously. I've tried to switch user contexts in my scripts via having an intermediate script that changes context to my VM user and then calling another script that does the work, but that doesn't seem to be working.
$scriptFile = $args[0]
$username = $args[1]
$password = $args[2]
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username,
$securePassword
Start-Process Powershell.exe -Credential $credential $scriptFile
Unfortunately it seems nothing gets run in the $scriptFile that I call, and I can't get any errors out of standard out/err, so I'm at a loss as to how this can be done.
Certainly someone out there has had to run scripts as another user via the Custom Script Execution method before, I'm hoping they happen to read this post.
Is there a way to set what user the Custom Script Execution runs as?
No, there is no way of setting a user under which script extension runs.
You also should use -PassThru and -Wait and\or -RedirectStandardError\-RedirectStandardInput to your command invocation. Also, add -ErrorAction Stop to your commands to propagate errors.