Creating PowerShell File Using New-Item & Add-Content Cmdlets - powershell

This is the first time posting on SO (and really on any public platform), so I apologize if this question was already answered or if the question isn't structured appropriately.
I am brand new to creating PowerShell Scripts and I'm hoping someone can assist me on my new scripting adventure!
The script I am trying to create is to gather user input on OS user credentials, the OS user password, and the remote server's IP Address\FQDN\Hostname. From there I want to create a ps1 file that a scheduled task will point to, which will copy a particular folder from one server to a remote server on a daily basis (replacing the remote servers folder). I am getting caught up on properly adding the needed lines using the New-Item and Add-Content cmdlets
Here is my script I created so far:
#Clear the Screen
Clear-Host
#Create Variable for OS User Account
$User = read-host "What is the OS User that has permissions to the remote web server?"
#Clear the Screen
Clear-Host
#Password for OS User Account
$Password = Read-Host "What is the password of the OS account that has permissions to the remote web server?"
#Clear the Screen
Clear-Host
#Convert Password String
$PWord = ConvertTo-SecureString -String $Password -AsPlainText -Force
#Combine User Name and Password into One Entity
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
#IP Address of Destination ICA Web Server
$DestServer = Read-Host "What is the IP address\FQDN\Hostname of the Destination Web Server"
#Create a PowerShell File that will be used for Task Scheduler
New-Item "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" -ItemType File -Force -Value "$PWord = ConvertTo-SecureString -String $Password -AsPlainText -Force"
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" ""
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" "$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord"
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" ""
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" "$Session = New-PSSession -ComputerName $DestServer -Credential $Credential"
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" "Copy-Item `"C:\Web\Web\Download`" -Destination `"C:\Web\Web\`" -ToSession $Session -Recurse -Force"
This is the results that I get in the ps1 that gets created (Used 'TestUser' for the OS user, 'PW' for the password, and '10.10.10.10' for the remote server):
System.Security.SecureString = ConvertTo-SecureString -String PW -AsPlainText -Force
System.Management.Automation.PSCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList TestUser, System.Security.SecureString
= New-PSSession -ComputerName 10.10.10.10 -Credential System.Management.Automation.PSCredential
Copy-Item "C:\Web\Web\Download" -Destination "C:\Web\Web\" -ToSession -Recurse -Force
On the first line, for some reason it displays 'System.Security.SecureString' rather than the $PWord variable.
The second line displays 'System.Management.Automation.PSCredential' & System.Security.SecureString rather than the $Credential & $PWord variables.
The third line does not display the $Session variable. It also displays 'System.Management.Automation.PSCredential' rather than the $Credential variable.
The fourth line does not display the $Session variable
So it looks like Powershell doesn't like me adding variables using the New-Item & Add-Content cmdlets.
Any input/suggestions is greatly appreciated!! Thank you!
UPDATE: Thank you, mklement0, for providing the missing piece to my puzzle!
Here is an updated working script based off the information provided by mklement0
#Clear the Screen
Clear-Host
#Create Variable for OS User Account
$User = read-host "What is the OS user account that has permissions to the remote web server?"
#Clear the Screen
Clear-Host
#Password for OS User Account
$Password = Read-Host "What is the password of the OS user account that has permissions to the remote web server?"
#Clear the Screen
Clear-Host
#Convert Password String
$PWord = ConvertTo-SecureString -String $Password -AsPlainText -Force
#Combine User Name and Password into One Entity
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
#IP Address of Destination ICA Web Server
$DestServer = Read-Host "What is the IP address, FQDN, or Hostname of the remote web server"
#Create a PowerShell File that will be used for Task Scheduler
New-Item "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" -ItemType File -Force -Value "`$OSUser = `"$User`""
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" ""
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" "`$PWord = ConvertTo-SecureString -String `"$Password`" -AsPlainText -Force"
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" "`$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList `$OSUser, `$PWord"
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" ""
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" "`$Session = New-PSSession -ComputerName `"$DestServer`" -Credential `$Credential"
Add-Content "C:\Test\ScheduledTask\CopyPasteDownLoadFolder.ps1" "Copy-Item `"C:\Web\Web\Download`" -Destination `"C:\Web\Web\`" -ToSession `$Session -Recurse -Force"

$ characters that you want to retain as-is inside an expandable (double-quoted) string ("...") must be escaped as `$, otherwise they and what follows are subject to string interpolation; e.g.:
$foo = 'bar'
# Note the ` (backtick) before the first $, which escapes it.
# The second $foo, which is unescaped is expanded (interpolated).
"Variable `$foo contains $foo"
The above yields verbatim:
Variable $foo contains bar

Related

Import-PFX as another user - Impersonation

I wanted to reach out and see if anyone has some tips on impersonation/runas cmds. I am working on a script that exports, then imports a .pfx certificate over to the users profile from the admin profile. Right now, I have everything working except for the import portion.
As seen below, I am showing only the import portion. $x and $y variables are defined earlier in the script by user input and that works okay.
Everything works up until the import-pfxcertificate cmdlet and scriptblock. Running that scriptblock as the other use is proving to be difficult. If anyone has any advice on how to structure that scriptblock cmd so that it will runas the user, that would be great!
I have an error log written into the script as well (not shown) Unfortunately, it is not picking up any errors because I believe it is pulling a local machine cert rather than the cert I specified - so no real error messages.
<#Cache credentials in IE and Import new or existing cert as client#>
function importcert
{
certpath = "C:\Temp\$x.pfx"
$password = $y | ConvertTo-SecureString -AsPlainText -Force
<#Enter your credentials#>
Credentials = Get-Credential -Credential corp\$x
<#Export to Secure XML#>
$Credentials | Export-Clixml -path 'C:\Temp\creds.xml'
<#Import credentials and run application using those credentials#>
Set-Location C:\
$creds = Import-Clixml -Path 'C:\Temp\creds.xml'
$ie = Start-Process -FilePath 'C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE' -Credential $creds
$ie
Start-Sleep -Seconds 30
<#Imports the certificate as the client#>
Start-Job -ScriptBlock { Import-PfxCertificate -FilePath $certpath -Exportable -CertStoreLocation Cert:\CurrentUser\My -Password $password } -Credential $creds
<#Search For Client Credential and if path is false, the credential file was removed successfully.#>
$clientXML = Test-Path -Path "C:\Temp\creds.xml"
Remove-Item -Path "C:\Temp\creds.xml"
if (-not ($clientXML))
{
Write-Output "Credential XML was removed"
}
}
importcert
It looks like all you're missing is some arguments for your Start-Job. I just tested this out locally and got it to install mycert.pfx for the other user TomServo:
<#Cache credentials in IE and Import new or existing cert as client#>
$Certpath = Get-Item "C:\Projects\Sandbox\mycert.pfx"
$Password = '{Password}' | ConvertTo-SecureString -AsPlainText -Force
<#Enter your credentials#>
$Credentials = Get-Credential -UserName TomServo
<#Export to Secure XML#>
$Credentials | Export-Clixml -path 'C:\Projects\Sandbox\creds.xml'
<#Import credentials and run application using those credentials#>
Set-Location C:\
$Creds = Import-Clixml -Path 'C:\Projects\Sandbox\creds.xml'
$Ie = Start-Process -FilePath 'C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE' -Credential $Creds
$Ie
Start-Sleep -Seconds 30
<#Imports the certificate as the client#>
Start-Job -ScriptBlock {
param($certpath, $Password)
Import-PfxCertificate -FilePath $Certpath -Exportable -CertStoreLocation Cert:\CurrentUser\My -Password $Password
} -Credential $Creds -ArgumentList $Certpath, $Password
<#Search For Client Credential and if path is false, the credential file was removed successfully.#>
$ClientXML = Test-Path -Path "C:\Projects\Sandbox\creds.xml"
Remove-Item -Path "C:\Projects\Sandbox\creds.xml"
if (-not ($ClientXML))
{
Write-Output "Credential XML was removed"
}

Credential Without Asking For Prompts In Powershell [duplicate]

I'd like to restart a remote computer that belongs to a domain. I have an administrator account but I don't know how to use it from powershell.
I know that there is a Restart-Computer cmdlet and that I can pass credential but if my domain is for instance mydomain, my username is myuser and my password is mypassword what's the right syntax to use it?
I need to schedule the reboot so I don't have to type the password.
The problem with Get-Credential is that it will always prompt for a password. There is a way around this however but it involves storing the password as a secure string on the filesystem.
The following article explains how this works:
Using PSCredentials without a prompt
In summary, you create a file to store your password (as an encrypted string). The following line will prompt for a password then store it in c:\mysecurestring.txt as an encrypted string. You only need to do this once:
read-host -assecurestring | convertfrom-securestring | out-file C:\mysecurestring.txt
Wherever you see a -Credential argument on a PowerShell command then it means you can pass a PSCredential. So in your case:
$username = "domain01\admin01"
$password = Get-Content 'C:\mysecurestring.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$serverNameOrIp = "192.168.1.1"
Restart-Computer -ComputerName $serverNameOrIp `
-Authentication default `
-Credential $cred
<any other parameters relevant to you>
You may need a different -Authentication switch value because I don't know your environment.
There is another way, but...
DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE
(It isn't a good idea to store passwords in scripts, but some of us just like to know how.)
Ok, that was the warning, here's the code:
$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$cred will have the credentials from John Doe with the password "ABCDEF".
Alternative means to get the password ready for use:
$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force
Regarding storing credentials, I use two functions(that are normally in a module that is loaded from my profile):
#=====================================================================
# Get-MyCredential
#=====================================================================
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = #"
Get-MyCredential
Usage:
Get-MyCredential -CredPath `$CredPath
If a credential is stored in $CredPath, it will be used.
If no credential is found, Export-Credential will start and offer to
Store a credential at the location specified.
"#
if($Help -or (!($CredPath))){write-host $Helptext; Break}
if (!(Test-Path -Path $CredPath -PathType Leaf)) {
Export-Credential (Get-Credential) $CredPath
}
$cred = Import-Clixml $CredPath
$cred.Password = $cred.Password | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
Return $Credential
}
And this one:
#=====================================================================
# Export-Credential
# Usage: Export-Credential $CredentialObject $FileToSaveTo
#=====================================================================
function Export-Credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
You use it like this:
$Credentials = Get-MyCredential (join-path ($PsScriptRoot) Syncred.xml)
If the credential file doesnt exist, you will be prompted the first time, at that point it will store the credentials in an encrypted string inside an XML file. The second time you run that line, the xmlfile is there and will be opened automatically.
I have to run SCOM 2012 functions from a remote server that requires a different credential. I avoid clear-text passwords by passing the output of a password decryption function as input to ConvertTo-SecureString. For clarity, this is not shown here.
I like to strongly type my declarations. The type declaration for $strPass works correctly.
[object] $objCred = $null
[string] $strUser = 'domain\userID'
[System.Security.SecureString] $strPass = ''
$strPass = ConvertTo-SecureString -String "password" -AsPlainText -Force
$objCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)
Here are two ways you could do this, if you are scheduling the reboot.
First you could create a task on one machine using credentials that have rights needed to connect and reboot another machine. This makes the scheduler responsible for securely storing the credentials. The reboot command (I'm a Powershell guy, but this is cleaner.) is:
SHUTDOWN /r /f /m \\ComputerName
The command line to create a scheduled task on the local machine, to remotely reboot another, would be:
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f /m \\ComputerName" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU "domain\username" /RP "password"
I prefer the second way, where you use your current credentials to create a scheduled task that runs with the system account on a remote machine.
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU SYSTEM /S ComputerName
This also works through the GUI, just enter SYSTEM as the user name, leaving the password fields blank.
I saw one example that uses Import/Export-CLIXML.
These are my favorite commands for the issue you're trying to resolve. And the simplest way to use them is.
$passwordPath = './password.txt'
if (-not (test-path $passwordPath)) {
$cred = Get-Credential -Username domain\username -message 'Please login.'
Export-CliXML -InputObject $cred -Path $passwordPath
}
$cred = Import-CliXML -path $passwordPath
So if the file doesn't locally exist it will prompt for the credentials and store them. This will take a [pscredential] object without issue and will hide the credentials as a secure string.
Finally just use the credential like you normally do.
Restart-Computer -ComputerName ... -Credentail $cred
Note on Securty:
Securely store credentials on disk
When reading the Solution, you might at first be wary of storing a password on disk.
While it is natural (and prudent) to be cautious of littering your hard drive with
sensitive information, the Export-CliXml cmdlet encrypts credential objects using the
Windows standard Data Protection API. This ensures that only your user account can
properly decrypt its contents. Similarly, the ConvertFrom-SecureString cmdlet also
encrypts the password you provide.
Edit: Just reread the original question. The above will work so long as you've initialized the [pscredential] to the hard disk. That is if you drop that in your script and run the script once it will create that file and then running the script unattended will be simple.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
$mycred.GetNetworkCredential().Password
Be very careful with storing passwords this way... it's not as secure as ...
Solution
$userName = 'test-domain\test-login'
$password = 'test-password'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $userName, $pwdSecureString
For Build Machines
In the previous code replace user name and password values by secret ("hidden from logs") environment variables of your build-machine
Test results by
'# Results'
$credential.GetNetworkCredential().Domain
$credential.GetNetworkCredential().UserName
$credential.GetNetworkCredential().Password
and you'll see
# Results
test-domain
test-login
test-password
This is what I use and works for me.
$User="Domain\Username"
$Password=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('VABlAHMAdABQAGEAcwBzAHcAbwByAGQA'))
$SecurePassword = New-Object -TypeName System.Security.SecureString
$Password.ToCharArray() | ForEach-Object {$SecurePassword.AppendChar($_)}
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword
And to get VABlAHMAdABQAGEAcwBzAHcAbwByAGQA I do this:
To Encode $EString means Encrypted String and $DString means Decrypted String
$EString = Read-Host "Type Text to Encode" -AsSecureString
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($EString)
$DString=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$Encoded=[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($DString))
$Encoded # VABlAHMAdABQAGEAcwBzAHcAbwByAGQA
$DString # TestPassword
That way I can put any password I want on the script without too much hassle.
In case below code might help someone.
function Get-RemoteConnection()
{
//$serverIp can be passed as a parameter of the function.
//I just make it static for testing.
$serverIp = '192.168.100.137'
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts $serverIp
Restart-Service WinRM
#Set credentials needed for remote installation
$userName = "administrator"
$password = ConvertTo-SecureString "2020core0515" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($userName, $password)
$session = New-PSSession -ComputerName $serverIp -Credential $cred
$a = Invoke-Command -Session $session -ScriptBlock { Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, #{label='UsedPercent'; expression={[Math]::Round((($_.size - $_.freespace) / $_.size) * 100, 2)}} }
Write-Host $a
return $session
}
function Delete-RemoteConnection($session)
{
Disconnect-PSSession $session | Out-Null
Disable-WSManCredSSP -Role Client
}
Instead of storing the encrypted password in a text file you can store it in the credential vault.
In the follwing example the user is prompted for a password only the first time, after that the password is retrieved from the credential vault.
# Load the Windows Runtime Class
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$Vault = New-Object Windows.Security.Credentials.PasswordVault
$RESOURCE = "myresource"
$USERNAME = "myuser"
try {
$credentials = $Vault.Retrieve($RESOURCE,$USERNAME)
$pwd = $credentials.Password | ConvertTo-SecureString -Key (1..16)
}
catch {
$pwd = Read-Host "please enter your password:" -AsSecureString
$Encrypted = ConvertFrom-SecureString -SecureString $pwd -Key (1..16)
$credentials = new-object -Type Windows.Security.Credentials.PasswordCredential -ArgumentList $RESOURCE,$USERNAME,$Encrypted
$Vault.Add($credentials)
}
$cred = New-Object System.Management.Automation.PsCredential($USERNAME,$pwd)
why dont you try something very simple?
use psexec with command 'shutdown /r /f /t 0' and a PC list from CMD.

How to provide unique credentials for Set-Content calls

I have a powershell script that simply updates a file on a couple different webservers. Each of these web servers have different local credentials that I need to provide in order to access the file in question. How can I update my script to allow for this?
#message
$statusMessage = "hello world"
#servers to update
$servers = #("1.1.1.1","2.2.2.2")
#update files
foreach ($server in $servers) {
Set-Content -Path "\\$server\c$\blah\foo.htm" -Value $statusMessage
}
Again, each server has it's own local Admin credentials that I need to use.
One way to do this, if you really are forced to use local accounts (avoiding this problem is one of the purposes of having a domain), is to authenticate on the server using net use, copy the file, then disconnect. Example:
$userName = Read-Host "Enter user name for computer1"
net use \\computer1\ipc$ /user:$userName *
Set-Content \\computer1\c$\whatever\file.htm "Content here"
net use \\computer1\ipc$ /delete
Of course you can generalize the computer name within the loop. In this example, you will have to manually enter the user name and password for each computer.
Since the -Credential parameter of Set-Content doesn't seem to actually work (as Bill_Stewart pointed out) you basically have 3 options AFAICS:
Use net use to authenticate a session as Bill suggested in his answer, then write to the UNC path.
Map a network drive, either via net use or the PoSh way:
$username = 'Administrator'
$password = ConvertTo-SecureString 'password' -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $password)
$drive = New-PSDrive -Name X -PSProvider FileSystem -Root "\\$server\c$\blah" -Persist -Credential $cred
Set-Content -Path 'X:\foo.htm' -Value $statusMessage
$drive | Remove-PSDrive
Run Set-Content on the remote server and have it write to a local path.
$username = 'Administrator'
$password = ConvertTo-SecureString 'password' -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $password)
Invoke-Command -Computer $server -ScriptBlock {
Param($msg)
Set-Content -Path C:\blah\foo.html -Value $msg
} -ArgumentList $statusMessage -Credential $cred
For both PowerShell approaches you'll have to prepare a PSCredential object as shown above, or just pass the username (in which case you'll be prompted for the password).

Create Local User with Custom User Folder in Powershell

I am trying to create a new Win 2008 server local user and assign the user a different profile path. I don't want Windows to generate all the files under C:\Users\newUser, instead, I'd like to have it do that in D:\customDir\newUser. Does anyone know of a way to do this?
So far this is what I have:
$users= #("U1","U2","U3")
$computer = [ADSI]"WinNT://$env:COMPUTERNAME,computer"
$group = [ADSI]"WinNT://$env:COMPUTERNAME/MyCustomGroup,group"
$users | foreach {
$userName = $_
$userPath = "D:\customDir\$userName"
echo "Creating $userName..."
$user = $computer.Create("User",$userName)
$user.put("description","User $userName Description")
#$user.put("profilePath",$userPath) #This does not work, throws an error
#$user.put("homeDirDrive","D:") #This appears to be ignored when uncommented
$user.setpassword($userName)
$user.setInfo()
$group.add($user.Path)
#run cmd from user account to create profile files/folders
$spw = ConvertTo-SecureString $userName -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $userName,$spw
Start-Process cmd /c -WindowStyle Hidden -Credential $cred -ErrorAction SilentlyContinue
}
The script successfully creates the users and adds them to the custom group, but all the files/folders end up in C:\Users\U*
To the OP,
Thanks for this piece, I was trying to figure out how to make this work for me:
run cmd from user account to create profile files/folders
$spw = ConvertTo-SecureString $userName -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $userName,$spw
Start-Process cmd /c -WindowStyle Hidden -Credential $cred -ErrorAction SilentlyContinue
but I had to modify the last line to get it to work:
Start-Process cmd /c -Credential $cred -ErrorAction SilentlyContinue -LoadUserProfile
This works fine.
$loginName="ChrisMcCormack"
$newPass="123456ABCDEFG" # obviously generate a proper password...
$desc="average user"
$localHost=[ADSI]"WinNT://localhost"
$newUser=$localHost.Create("user",$loginName);
$newUser.setPassword($newPass);
$newUser.put("HomeDirectory","c:\users\$loginName");
$newUser.put("description",$desc);
$newUser.setInfo();
You can also use:
$spw = ConvertTo-SecureString $newPass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $loginName,$spw
Start-Process cmd /c -WindowStyle Hidden -Credential $cred -ErrorAction SilentlyContinue
to create the users directories without logging the user on.
Chris
Here is the way I use according to the underlaying COM component object model and the IADsUser interface.
$obj = [ADSI]"WinNT://$env:COMPUTERNAME"
$user1=$obj.create("user", "utilisateur1")
$user1.PasswordExpired=0
$user1.Invoke("setpassword","test.2012")
$user1.Invoke("put", "HomeDirectory", "c:\silogix")
$user1.Invoke("put", "Profile", "c:\docs")
$user1.Invoke("put", "LoginScript", "test.cmd")
$user1.CommitChanges()
Here is the result.
The only thing I can think of for you would be to change it at the registry level. Note that I'm not recommending you mess with the registry, but this does do what you want -
The default directory for a new profile is determined by the ProfilesDirectory in HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList, and by default is %SystemDrive%\Users, changing it to $userpath should do what you want -
$regpath = "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
$regname = "ProfilesDirectory"
set-itemproperty -path $regpath -name $regname -value $userpath
Hope that helps!

Using PowerShell credentials without being prompted for a password

I'd like to restart a remote computer that belongs to a domain. I have an administrator account but I don't know how to use it from powershell.
I know that there is a Restart-Computer cmdlet and that I can pass credential but if my domain is for instance mydomain, my username is myuser and my password is mypassword what's the right syntax to use it?
I need to schedule the reboot so I don't have to type the password.
The problem with Get-Credential is that it will always prompt for a password. There is a way around this however but it involves storing the password as a secure string on the filesystem.
The following article explains how this works:
Using PSCredentials without a prompt
In summary, you create a file to store your password (as an encrypted string). The following line will prompt for a password then store it in c:\mysecurestring.txt as an encrypted string. You only need to do this once:
read-host -assecurestring | convertfrom-securestring | out-file C:\mysecurestring.txt
Wherever you see a -Credential argument on a PowerShell command then it means you can pass a PSCredential. So in your case:
$username = "domain01\admin01"
$password = Get-Content 'C:\mysecurestring.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$serverNameOrIp = "192.168.1.1"
Restart-Computer -ComputerName $serverNameOrIp `
-Authentication default `
-Credential $cred
<any other parameters relevant to you>
You may need a different -Authentication switch value because I don't know your environment.
There is another way, but...
DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE
(It isn't a good idea to store passwords in scripts, but some of us just like to know how.)
Ok, that was the warning, here's the code:
$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$cred will have the credentials from John Doe with the password "ABCDEF".
Alternative means to get the password ready for use:
$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force
Regarding storing credentials, I use two functions(that are normally in a module that is loaded from my profile):
#=====================================================================
# Get-MyCredential
#=====================================================================
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = #"
Get-MyCredential
Usage:
Get-MyCredential -CredPath `$CredPath
If a credential is stored in $CredPath, it will be used.
If no credential is found, Export-Credential will start and offer to
Store a credential at the location specified.
"#
if($Help -or (!($CredPath))){write-host $Helptext; Break}
if (!(Test-Path -Path $CredPath -PathType Leaf)) {
Export-Credential (Get-Credential) $CredPath
}
$cred = Import-Clixml $CredPath
$cred.Password = $cred.Password | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
Return $Credential
}
And this one:
#=====================================================================
# Export-Credential
# Usage: Export-Credential $CredentialObject $FileToSaveTo
#=====================================================================
function Export-Credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
You use it like this:
$Credentials = Get-MyCredential (join-path ($PsScriptRoot) Syncred.xml)
If the credential file doesnt exist, you will be prompted the first time, at that point it will store the credentials in an encrypted string inside an XML file. The second time you run that line, the xmlfile is there and will be opened automatically.
I have to run SCOM 2012 functions from a remote server that requires a different credential. I avoid clear-text passwords by passing the output of a password decryption function as input to ConvertTo-SecureString. For clarity, this is not shown here.
I like to strongly type my declarations. The type declaration for $strPass works correctly.
[object] $objCred = $null
[string] $strUser = 'domain\userID'
[System.Security.SecureString] $strPass = ''
$strPass = ConvertTo-SecureString -String "password" -AsPlainText -Force
$objCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)
Here are two ways you could do this, if you are scheduling the reboot.
First you could create a task on one machine using credentials that have rights needed to connect and reboot another machine. This makes the scheduler responsible for securely storing the credentials. The reboot command (I'm a Powershell guy, but this is cleaner.) is:
SHUTDOWN /r /f /m \\ComputerName
The command line to create a scheduled task on the local machine, to remotely reboot another, would be:
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f /m \\ComputerName" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU "domain\username" /RP "password"
I prefer the second way, where you use your current credentials to create a scheduled task that runs with the system account on a remote machine.
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU SYSTEM /S ComputerName
This also works through the GUI, just enter SYSTEM as the user name, leaving the password fields blank.
I saw one example that uses Import/Export-CLIXML.
These are my favorite commands for the issue you're trying to resolve. And the simplest way to use them is.
$passwordPath = './password.txt'
if (-not (test-path $passwordPath)) {
$cred = Get-Credential -Username domain\username -message 'Please login.'
Export-CliXML -InputObject $cred -Path $passwordPath
}
$cred = Import-CliXML -path $passwordPath
So if the file doesn't locally exist it will prompt for the credentials and store them. This will take a [pscredential] object without issue and will hide the credentials as a secure string.
Finally just use the credential like you normally do.
Restart-Computer -ComputerName ... -Credentail $cred
Note on Securty:
Securely store credentials on disk
When reading the Solution, you might at first be wary of storing a password on disk.
While it is natural (and prudent) to be cautious of littering your hard drive with
sensitive information, the Export-CliXml cmdlet encrypts credential objects using the
Windows standard Data Protection API. This ensures that only your user account can
properly decrypt its contents. Similarly, the ConvertFrom-SecureString cmdlet also
encrypts the password you provide.
Edit: Just reread the original question. The above will work so long as you've initialized the [pscredential] to the hard disk. That is if you drop that in your script and run the script once it will create that file and then running the script unattended will be simple.
read-host -assecurestring | convertfrom-securestring | out-file C:\securestring.txt
$pass = cat C:\securestring.txt | convertto-securestring
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist "test",$pass
$mycred.GetNetworkCredential().Password
Be very careful with storing passwords this way... it's not as secure as ...
Solution
$userName = 'test-domain\test-login'
$password = 'test-password'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $userName, $pwdSecureString
For Build Machines
In the previous code replace user name and password values by secret ("hidden from logs") environment variables of your build-machine
Test results by
'# Results'
$credential.GetNetworkCredential().Domain
$credential.GetNetworkCredential().UserName
$credential.GetNetworkCredential().Password
and you'll see
# Results
test-domain
test-login
test-password
This is what I use and works for me.
$User="Domain\Username"
$Password=[Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('VABlAHMAdABQAGEAcwBzAHcAbwByAGQA'))
$SecurePassword = New-Object -TypeName System.Security.SecureString
$Password.ToCharArray() | ForEach-Object {$SecurePassword.AppendChar($_)}
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword
And to get VABlAHMAdABQAGEAcwBzAHcAbwByAGQA I do this:
To Encode $EString means Encrypted String and $DString means Decrypted String
$EString = Read-Host "Type Text to Encode" -AsSecureString
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($EString)
$DString=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$Encoded=[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($DString))
$Encoded # VABlAHMAdABQAGEAcwBzAHcAbwByAGQA
$DString # TestPassword
That way I can put any password I want on the script without too much hassle.
In case below code might help someone.
function Get-RemoteConnection()
{
//$serverIp can be passed as a parameter of the function.
//I just make it static for testing.
$serverIp = '192.168.100.137'
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts $serverIp
Restart-Service WinRM
#Set credentials needed for remote installation
$userName = "administrator"
$password = ConvertTo-SecureString "2020core0515" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($userName, $password)
$session = New-PSSession -ComputerName $serverIp -Credential $cred
$a = Invoke-Command -Session $session -ScriptBlock { Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" | Select-Object DeviceID, #{label='UsedPercent'; expression={[Math]::Round((($_.size - $_.freespace) / $_.size) * 100, 2)}} }
Write-Host $a
return $session
}
function Delete-RemoteConnection($session)
{
Disconnect-PSSession $session | Out-Null
Disable-WSManCredSSP -Role Client
}
Instead of storing the encrypted password in a text file you can store it in the credential vault.
In the follwing example the user is prompted for a password only the first time, after that the password is retrieved from the credential vault.
# Load the Windows Runtime Class
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$Vault = New-Object Windows.Security.Credentials.PasswordVault
$RESOURCE = "myresource"
$USERNAME = "myuser"
try {
$credentials = $Vault.Retrieve($RESOURCE,$USERNAME)
$pwd = $credentials.Password | ConvertTo-SecureString -Key (1..16)
}
catch {
$pwd = Read-Host "please enter your password:" -AsSecureString
$Encrypted = ConvertFrom-SecureString -SecureString $pwd -Key (1..16)
$credentials = new-object -Type Windows.Security.Credentials.PasswordCredential -ArgumentList $RESOURCE,$USERNAME,$Encrypted
$Vault.Add($credentials)
}
$cred = New-Object System.Management.Automation.PsCredential($USERNAME,$pwd)
why dont you try something very simple?
use psexec with command 'shutdown /r /f /t 0' and a PC list from CMD.