Using 'net use' through PowerShell exhibits different behaviour when done through cmd on a Windows Server 2012 instance - powershell

I have a cloud service with the following line of code in startup.cmd:
net use n: \\<storage-account>.file.core.windows.net\scorm /u:<storage-account> <storage-password>
This successfully creates the mapped drive to point to the Azure File Services share, but it shows in Windows explorer as a disconnected drive and any attempt to remove it using the 'Disconnect' option results in a "This network connection does not exist" although if I double click the folder I am successfully able to access the files.
If I run the same command through a cmd prompt the drive shows as connected with the name of the share and the path displayed. Do I need to do anything different in the PowerShell startup command to render the same results as the cmd line prompt?

The "net use" command only connects to the share in the context you are running. So you will have to run the "net use" in the same context your role will run.
For web roles this will be "NT AUTHORITY\NETWORK SERVICE". To run "net use" in that context, you need a tool like psexec.exe, which you can download from Windows Sysinternals.
Place psexec.exe into your role's bin directory, and set up an elevated startup script with this command:
psexec -accepteula -u "NT AUTHORITY\NETWORK SERVICE" net use n: \\<storage-account>.file.core.windows.net\test /u:<storage-account> <storage-password>

Drives are mapped to your user token, and administrators have two tokens. Limited and elevated. Make sure you are using consistent tokens. I.e. if mapped while Run As Aministrator then only programs running elevated can access that mapping.

Related

PsExec64.exe to encrypt password and sore is throwing error

I am new to power shell scripting. I have used below piece to encrypt and store password:
$password = "TestingWithSamplePassword"
$salt = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 10 | % {[char]$_})
$encryptPasswordFile = "& script_path\PsExec64.exe -accepteula -nobanner -s powershell -Command {$password|ConvertTo-SecureString -Force -AsPlainText|ConvertFrom-SecureString}"
Invoke-Expression -Command:$encryptPasswordFile
It fails with below error:
PsExec executes a program on a remote system, where remotely executed console
applications execute interactively.
Usage: psexec [\\computer[,computer2[,...] | #file]][-u user [-p psswd][-n s][-r servicename][-h][-l][-s|-e][-x][-i [se
ssion]][-c [-f|-v]][-w directory][-d][-][-a n,n,...] cmd [arguments]
-a Separate processors on which the application can run with
commas where 1 is the lowest numbered CPU. For example,
to run the application on CPU 2 and CPU 4, enter:
"-a 2,4"
-c Copy the specified program to the remote system for
execution. If you omit this option the application
must be in the system path on the remote system.
-d Don't wait for process to terminate (non-interactive).
-e Does not load the specified account's profile.
-f Copy the specified program even if the file already
exists on the remote system.
-i Run the program so that it interacts with the desktop of the
specified session on the remote system. If no session is
specified the process runs in the console session.
-h If the target system is Vista or higher, has the process
run with the account's elevated token, if available.
-l Run process as limited user (strips the Administrators group
and allows only privileges assigned to the Users group).
On Windows Vista the process runs with Low Integrity.
-n Specifies timeout in seconds connecting to remote computers.
-p Specifies optional password for user name. If you omit this
you will be prompted to enter a hidden password.
-r Specifies the name of the remote service to create or interact.
with.
-s Run the remote process in the System account.
-u Specifies optional user name for login to remote
computer.
-v Copy the specified file only if it has a higher version number
or is newer on than the one on the remote system.
-w Set the working directory of the process (relative to
remote computer).
-x Display the UI on the Winlogon secure desktop (local system
only).
-arm Specifies the remote computer is of ARM architecture.
-priority Specifies -low, -belownormal, -abovenormal, -high or
-realtime to run the process at a different priority. Use
-background to run at low memory and I/O priority on Vista.
computer Direct PsExec to run the application on the remote
computer or computers specified. If you omit the computer
name PsExec runs the application on the local system,
and if you specify a wildcard (\\*), PsExec runs the
command on all computers in the current domain.
#file PsExec will execute the command on each of the computers listed
in the file.
cmd Name of application to execute.
arguments Arguments to pass (note that file paths must be
absolute paths on the target system).
-accepteula This flag suppresses the display of the license dialog.
-nobanner Do not display the startup banner and copyright message.
You can enclose applications that have spaces in their name with
quotation marks e.g. psexec \\marklap "c:\long name app.exe".
Input is only passed to the remote system when you press the enter
key, and typing Ctrl-C terminates the remote process.
If you omit a user name the process will run in the context of your
account on the remote system, but will not have access to network
resources (because it is impersonating). Specify a valid user name
in the Domain\User syntax if the remote process requires access
to network resources or to run in a different account. Note that
the password and command is encrypted in transit to the remote system.
Error codes returned by PsExec are specific to the applications you
execute, not PsExec.
Help would be highly appreciated..
Try this:
$encryptPasswordFile = "& 'script_path\PsExec64.exe -accepteula -nobanner -s powershell -Command {$password|ConvertTo-SecureString -Force -AsPlainText|ConvertFrom-SecureString}'"

How would I run a batch file remotely over sccm in interactive cmd (micro right click tools)

On SCCM you can right click --> Micro right click tools and interactive command prompt this uses PS exec to open a remote cmd session on the selected PC.
From this if a run a .bat file form a server share it comes back as access denied,
However the runas command e.g.
runas /Administrator cmd.exe /c "\\svr-sccm\ad$\!!! User cleanup batchfiles\Delete all user no input.bat"
Runs with no errors but doesn't seem to actually do anything (the bat file calls delprof2 to clean user profiles off of the C drive and registry)
Any suggestions on how I would be able to run the bat file remotely on a PC when a Non-admin user is logged in (without remote controlling)
Any suggestions would be appreciated.
Access Denied most likely signals you, that the user, which runs the command, does not have access to the share, that you are trying to access.
If your command really spins up a commandline with psexec, it will run in SYSTEM context, i.e. the computer on which you run the script, must have access to the file share.

Run specific commands in PowerShell under different credentials?

I am trying to run a specific command line function in my PowerShell script. The catch is the command needs elevated permissions to be able to execute.
Here is a condensed example:
# PowerShell code...
query session /server:"SERVERNAME" #NEEDS ELEVATED PERMISSIONS
# More PowerShell code
The query command needs to be run under elevated permissions.
I have tried the following:
Invoke-Command -ScriptBlock {
query session /server:"SERVERNAME"
} -Credential get-credential
But this doesn't work because the -ComputerName parameter needs to be present when using a -Credential parameter. I want to be able to run this without using a remote server.
I know I can get around it by having the users start up PowerShell under their elevated account credentials, but I'd rather just prompt for credentials while the script runs and just run that single command under their administrator account credentials. Everything else the script does is fine under normal credentials.
There are some add-ins for PowerShell, but I actually found the simplest way was to:
Sysinternals in regular command line
With the PSexec process, you can pass IP address, usermame, and password
Fiddle with it to a point you're happy
Create a batch file to then run from PowerShell if that is the desired deploy to environment
When creating the method, have it consume parameters if you want the call out to be dynamic and consume different usernames/passwords/IP addresses to log into
If the exec will always run on "computerA" using "loginA" and "pwA" then there is obviously no need to parameterize
*Sysinternals cannot be used to outright hack a terminal. The user of a remote exec must first have the same Sysinternals tools installed to the system that is to accept remote executables, that tool must be opened once and given GUI-based approval to allow run on said system must be physically addressed.
Note: Any remote PSexec's using credentials will execute with the same level of permissions that the provided username/password is granted on that system.
Here is the link: (PsExec v2.2). Although I recommend going a level or two up and downloading the entire toolbox.

psexec double backslash error

I am trying to run the following command in power shell but it keeps giving me error at the double back slash character.. what do i do!! I saw other forums and this yntax works fine for them!
$combined="C:\tools\PsExec.exe \\computer cmd.exe"
PS C:\Users\Desktop\initialutility\initutil_v2> Invoke-Expression $combined
At :line:1 char:20
+ C:\tools\PsExec.exe <<<< \\computer cmd.exe
I substituted \computer with \x.x.x.x (i.e Ip address)..still no use..
Please help!
I believe your problem lies elsewhere as double slashes work fine e.g.:
PS> $command = "c:\bin\psexec.exe \\genericpc1 hostname.exe"
PS> iex $command
PsExec v1.98 - Execute processes remotely
Copyright (C) 2001-2010 Mark Russinovich
Sysinternals - www.sysinternals.com
GENERICPC1
hostname.exe exited on genericpc1 with error code 0.
I would try running psexec.exe outside the context of Invoke-Expression and get that working first. Another issue with using psexec is that it uses your credentials if you don't specify any credentials. That means, your credentials need to work on the remote system.
Other requirements, from an article on PsExec are:
PsExec's ability to run processes remotely requires that both the
local and remote computers have file and print sharing (i.e., the
Workstation and Server services) enabled and that the default Admin$
share (a hidden share that maps to the \windows directory) is defined
on the remote system.
... impersonates the account from which you run PsExec on the local
system. Impersonation is somewhat restricted from the perspective of
security—the remote process doesn't have access to any network
resources, even those that your account typically would be able to
access. If the account in which you're running doesn't have local
administrative privileges on the remote system, the process you want
to run requires access to network resources, or you want to run a
process in a different account, then use PsExec's -u switch to provide
an alternative account name.
share (a hidden share that maps to the \windows directory) is defined
on the remote system.

Batch files, Powershell Scripts, PSExec and System user

I'm trying to put in place some monitoring for Windows Task Scheduler, I have a Powershell script that runs the following:
$serverName = hostname
$schedule = new-object -com("Schedule.Service")
$schedule.connect($serverName)
$tasks = $schedule.getfolder("\").gettasks(0)
$tasks |select name, lasttaskresult, lastruntime
This returns a list of scheduled tasks on the server it is run on, the last task result and last run time. The purpose for this is to return a dataset to our monitoring solution (Geneos) which we can use for alerting.
We have a large Win2008 estate, so I want the script centralised allowing any of the Geneos probes to call it and return a dataset for their host. To do this I wrapped the powershell in a .bat file which does the following:
\\fileserverhk\psexec.exe -accepteula -u admin -p "pwd" powershell.exe cpi \\fileserverhk\scripts\TaskSchedulerMonitor.ps1 -Destination C:\Monitor\TaskSchedulerMonitor.ps1
\\fileserverhk\psexec.exe -accepteula -u admin -p "pwd" powershell.exe -ExecutionPolicy Bypass -File C:\Monitor\TaskSchedulerMonitor.ps1
The First step copies the .ps1 file locally to get around Powershell not trusting UNC paths and the second part runs the script.
If I run the .bat file manually from a test server it executes fine (this is logged in under an admin account). However, when I fire the .bat file via Geneos (which runs under the SYSTEM account) I get:
Access is denied.
PsExec could not start powershell.exe:
So basically my question is, how do I get PsExec to switch user when it is run under the SYSTEM account? Even though PsExec has the credentials set for another account, there is obviously something preventing it from changing when run under system.
I read to try running it with the -h switch but I get the below error:
The handle is invalid.
Connecting to local system...
Starting PsExec service on local system...
Connecting with PsExec service on <server>...
Starting powershell.exe on <server>...
Error communicating with PsExec service on <server>:
In addition to the above error, I end up with the PSExec and powershell processes hung on the remote machine. The interesting part is I can see the PSExec and PSEXEC.SVC running under SYSTEM and the powershell running under admin, so it's almost there, but something isn't quite right there.
We managed to get there using a powershell wrapper on the Windows schtasks command (link here). Schtasks can be run under the SYSTEM account and will return all the necessary task information, so we no longer needed to faff about with permissions, and no more clear text passwords on the environment (bonus).
We wrapped:
schtasks.exe Query /FO CSV
in a powershell script, and used PS to format the output into the csv style expected by Geneos.