Automate user homedirectory creation Powershell - windows

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/

Related

delete windows.old remotely with powershell

at the moment in our company we are upgrading our windows 10 to the newest built. after the upgrade we have the windows.old folder directly under c: sometimes this folder is extremly big. how can i delete this folder remotely with powershell.
if i try to delete this folder with the explorer with \pc-name\c$ i don't have the permissions. now i want to get the acl for the folder and all subfolders with powershell but i only get the acl for the top folder. how can i get it working for the complete directory. is there any other way to delete windows.old remotly?
$computername = read-host "enter pc"
$script = {
# set ErrorAction to 'Stop' in order to catch errors
$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
# you're now running this on the remote pc, so use local path
$path = Get-ChildItem -Directory -Path "C:\windows.old\" -recurse
try {
$acl = Get-Acl -path $path.FullName
$accessrule = [System.Security.AccessControl.FileSystemAccessRule]::new('username', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$acl.SetAccessRule($accessRule)
$acl | Set-Acl -path $path.FullName
# output the message
"{0}`t{1} success" -f (Get-Date).ToString(), $env:COMPUTERNAME
}
catch {
"{0}`t{1} failed" -f (Get-Date).ToString(), $env:COMPUTERNAME
}
# restore previous ErrorAction
$ErrorActionPreference = $oldErrorAction
}
$result = Invoke-Command -ComputerName $computername -ScriptBlock $script
if ($result -ne $null)
{
write-host "sucess" -ForegroundColor "green"
}
else
{
write-host "no success" -ForegroundColor "red"
}

powershell start-process as admin, am i misssing something

Im trying to create a script where a domain user would be able to run IIS service on windows as a local admin using stored credentials.
$adminerpath = 'c:\programdata\adminer'
Function StoreCreds(){
$credential = Get-Credential
$credential | Export-CliXml -Path $adminerpath\data.dat
}
if (Test-Path $adminerpath){
$credential = Import-CliXml -Path $adminerpath\data.dat
Start-Process C:\windows\System32\inetsrv\InetMgr.exe -Credential ($credentials)
}
else {
New-Item -Path $adminerpath -ItemType "directory"
attrib +h c:\programdata\adminer | Out-Null
StoreCreds
}
very simple, should see if the credential is stored and then run process with -credential.
it works with anything else (like note.exe or pwoershell.exe), but when i try running this with InetMgr.exe im getting:
start-process : This command cannot be run due to the error: The requested operation requires elevation.
any help would be much appriciated

Continue powershell script execution after system restart from last execution point

What i'm trying to do ?
Create four files in local disk in the following order.
Note : In my local machine and not in any server remotely.
Three files to be created
Restart the system
On system startup create another file
Script i have used.
get-job | remove-job -Force
function create-file {
Param ([string] $a)
$p = "D:\" + $a
Write-Host $p
if (!(Test-Path $p))
{
New-Item -path D:\$a -type "file" -value "my new text"
Write-Host "Created new file and text content added"
}
else
{
Add-Content -path D:\$a -value "new text content"
Write-Host "File already exists and new text content added"
}
}
Workflow New-ServerSetup
{
create-file "one.txt"
create-file "two.txt"
create-file "three.txt"
Restart-Computer -ComputerName $env:COMPUTERNAME -Wait
Start-Sleep -Seconds 7
create-file "four.txt"
Unregister-ScheduledJob -Name NewServerSetupResume
}
$adm = "####"
$pwd = ConvertTo-SecureString -String "####" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($adm, $pwd)
$AtStartup = New-JobTrigger -AtStartup
Register-ScheduledJob -Name NewServerSetupResume -Credential $cred -Trigger $AtStartup -ScriptBlock {Import-Module PSWorkflow; Get-Job -Name NewSrvSetup -State Suspended | Resume-Job}
New-ServerSetup -JobName NewSrvSetup
Issues i'm facing
The execution returns Cannot wait for local computer to restart
i'm new to powershell things if any mistakes burden me.
Thanks in advance.
Schedule a job first, then reboot without waiting.

PowerShell_copy-item_ToSession/FromSession

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.

Changing share permissions using Powershell

I'm trying to modify the share permissions of share drives on a bunch of windows servers which are running either 2008 R2 or 2012.
I worked up a script which you can find here:
Import-Module ActiveDirectory
$list = Get-ADComputer -Filter 'SamAccountName -like "*FP*"' | Select -Exp Name
foreach ($Computer in $list)
{
Grant-SmbShareAccess -Name User -CimSession Server -AccountName "username" -AccessRight Full -confirm:$false
$acl = (Get-Item \\$Computer\d$\User ).GetAccessControl('Access')
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule ("Corp\uc4serv","FullControl","ContainerInherit, ObjectInherit","None","Allow")
$acl.AddAccessRule($rule)
Set-Acl \\$Computer\d$\User $acl
Write-Host -ForegroundColor DarkGreen "Permissions granted on $Computer"
}
Write-Host -ForegroundColor DarkBlue "Command Has Completed"
But it doesn't work on 2008 servers presumably because they can't run the Get-SmbShareAccess cmdlet.
What I'm trying to do is very similar to this post here: How to set share permissions on a remote share with Powershell? but specifically on Windows servers.
I also found this code on a website (http://windowsitpro.com/powershell/managing-file-shares-windows-powershell):
$acl = Get-Acl `
\\servername\c$\Users\username\sharetest
$permission = "corp\uc4serv","FullControl","Allow"
$accessRule = New-Object `
System.Security.AccessControl.FileSystemAccessRule `
$permission
$acl.SetAccessRule($accessRule)
$acl |
Set-Acl \\servername\c$\Users\username\sharetest
But this just sets the Security on the share instead of the share permissions.
I also looked into using the Net Share command but in order to change share permissions with that, it has to delete and re-create the share drive completely.
You can use "Net Share". Use Invoke-Command to run it on each remote server.
Source - https://social.technet.microsoft.com/Forums/windowsserver/en-US/3edcabac-f1a8-4c4a-850c-8ba4697930a2/using-net-share-within-powershell
Example
Source - $server = "MYSRV" ; $user = "username" ; $SrvPath = "E:\Users\$user"
$sb = {
param($User,$SrvPath)
NET SHARE $User$=$SrvPath "/GRANT:Domain Admins,FULL" "/GRANT:$User,CHANGE" /REMARK:"Home folder for $SrvPath"
}
Invoke-Command -Computername "$Server" -ScriptBlock $sb -ArgumentList $user,$SrvPath

Resources