Inactive Computers Script - powershell

I wrote a PowerShell script that will check AD for computers that haven't authenticated with it in 30 days. It will then disable the workstations and move them to another OU. It will also create a list and export the CSV file to the C:\Custom Folder. However, I need the script to run as administrator.
$DaysInactive = 30
$time = (Get-Date).Adddays(-($DaysInactive))
Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -ResultPageSize 2000 -resultSetSize $null -Properties Name, OperatingSystem, SamAccountName, DistinguishedName | Move-ADObject -TargetPath "OU=Inactive,OU=Workstations,DC=genericname,DC=genericname,DC=genericname,DC=genericname" -PassThru |Set-ADComputer -Enabled $False -PassThru |Export-Csv -Path "\\SERVERNAME\c$\IT Documentation\Inactive Computers\inactivecomputers.csv" -NoTypeInformation
I am working on setting the script to run automatically through task scheduler every Friday. How would I need to modify the script to accomplish this?
If I launch PowerShell manually by right clicking and select run as administrator. The script works fine. It's not working through task scheduler though. Any thoughts?
Would I use:
Start-Process powershell -Verb runAs
If so where would I need to insert it?

Good Job. That looks pretty good.
Have a look at these instructions to make a scheduled task out of a script. The short of it is, you open the task scheduler and run powershell.exe with your script in the arguments.
Keep in mind that you will need to run a job that touches AD as yourself, and if you change your password while this job is enabled, it could lock you out by attempting to log in multiple times.

Related

Set-GPPermission correctly in a script

I started to write a script for my domain but not sure how to finish it.
I got a GPO to turn off Windows firewall without an option to turn it on for endpoint computers in the domain.
I want the new computers to be added to this GPO with the permission "deny all" I'm just not sure how to finish it, this is what I've got so far:
$Limit=(Get-Date).AddDays(-7)
$NewPC=Get-ADComputer -Filter {whenCreated -gt $limit} -Properties whenCreated
$NewPC | ForEach-Object Set-GPPermission -Name <GPO_Name> -TargetType Group -PermissionLevel PermissionLevel
the two 1st lines just to get the list of the computers which is working well, but I've some kind of trouble in the last line, actually getting the computers into the GPO and to set the permissions right, I tried a few methods but I can't get to work, what am I doing wrong here?
After several tries, I managed to figure out a solution to make it work, just keep in mind that, In my environment the PC's are redirected to a different location from the Computer container to an OU and and the principle name is no longer in use so I used the name only.
$NewPC | ForEach-Object {Set-GPPermission -Name <GPO> -TargetType Computer -TargetName $NewPC -PermissionLevel GpoApply}

Command to Unlock a locked domain user

I'v been using these to list locked users in my domain and prompt me for input samaccountname to unlock desired one:
I did it with 3 file.
first one is ps1 to list all of them
import-module activedirectory
search-adaccount -lockedout | select name, samaccountname, OU
second one is another ps1 file:
$user = Read-Host "Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list"
Search-ADAccount -LockedOut | Where {$_.samaccountname -eq $user} | Unlock-ADAccount
and for executing above files, i use a .bat file:
:loop
powershell.exe -ExecutionPolicy Bypass -File c:\ps\lockedlist.ps1
powershell.exe -ExecutionPolicy Bypass -File c:\ps\unlock.ps1
cls
goto loop
and when i run it... it list all locked users and i can copy paste each samaacount name to unlock them
BUT the problem is,when I want to do it with ONE ps1 file it doesnt work. it just ask for samaccountname but it doesnt list it
import-module activedirectory
search-adaccount -lockedout | select name, samaccountname, OU
$user = Read-Host "Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list"
Search-ADAccount -LockedOut | Where {$_.samaccountname -eq $user} | Unlock-ADAccount
i know .bat file will be pretty same...
thanks to anyone who reads and helps.
Powershell always tries to optimize the output it gives for you. So the order of the output might not be the same as you expect it from the commands you have in a script. If possible it will concatenate output to be more readable especially when it's the same type of objects. To break this you could use a format cmdlet like Format-Table par example.
Search-ADAccount -LockedOut |
Select-Object -Property Name, sAMAccountName, DistinguishedName |
Format-Table
$user = Read-Host -Prompt 'Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list'
Search-ADAccount -LockedOut |
Where-Object -FilterScript {$_.samaccountname -eq $user} |
Unlock-ADAccount
At least, it worked in my environment.
And BTW: Since Powershell version 3 you don't need to explicitly import the modules anymore. They will be imported automaticaly. Better would be to use a #Requires statement like #Requires -Modules activedirectory on top of the script. That would even prevent the script to run if there's no active directory module installed

How to get full SID from powershell AD module and run in SSIS

I m developing a SSIS package to get all disabled account from AD. I want to get the full SID and put into a file. But it not allow me to do that.
Right now I m having this code which works fine in my package:
-executionpolicy remotesigned -command "import-module activedirectory; search-adaccount -accountdisabled |ft SamAccountName, SID" >d:\scripts\disabledaccount\DisabledAccount.txt
But this only returns SID like: S-1-5-21-1219070818-4200922009-29827...
So I need the full SID. I tried to run this code in Powershell AD :
import-module activedirectory; search-adaccount -accountdisabled |ft SamAccountName,#{Label="SID";Expression={$_.SID};width=50;align="left"} >d:\scripts\disabledaccount\DisabledAccount.txt
and it works fine. but when I try to run it in SSIS package it doesn't work because of #{Label="SID";Expression={$_.SID};width=50;align="left"} this part.
Can any one let me know what should I put there to get the full SID?
Instead of 'ft' (Format-Table), use Select-Object instead. The Format-* cmdlets are actually manipulating the text to make it fit best in the console window; you don't want that. Just try
Search-ADAccount -AccountDisabled | Select-Object SamAccountName, SID
and see that that gets you.

exporting Powershell Script to CSV

We are getting ready to merge our AD with another. We have about 300 computers that I'm trying to match up with who uses them so the accounts and home folders migrate correctly, and I'm trying to think of the most efficient way to get this information.
We have everyone in an inventory system (Filemaker) (and will be implementing SCCM once we migrate (thank god) ) but we had a few errors when we did our first test batch. Im looking for something I can push out through group policy (possibly?) that will give me the computer name, logged in account, and them email it to me.
So far this is what I have.
[System.Environment]::UserName
[System.Environment]::UserDomainName
[System.Environment]::MachineName
Out-File T:\TEST.txt
But the output is blank. Any idea what I'm doing wrong here? Also is there a way to have this run on multiple computers but write to the same file?
"$env:USERNAME,$env:USERDOMAIN,$env:COMPUTERNAME" | Out-File 'T:\test.txt'
will write the name and domain of the currently logged-in user as well as the hostname of the local computer to the file T:\test.txt.
Using a single file may cause conflicts due to concurrent write attempts, though. It's better to use one file per computer, like this:
"$env:USERDOMAIN\$env:USERNAME" | Out-File "T:\$env:COMPUTERNAME.txt"
Run it as a logon script (or from a logon script), e.g. like this:
powershell -ExecutionPolicy Bypass -File "\\%USERDNSDOMAIN\netlogon\your.ps1"
Get-ADComputer -Filter * -Property * | Select-Object Name | Out-File C:\outdir\machinelist.txt -NoTypeInformation -Encoding UTF8
will get you all machine names, unless you have them already. Either way, use your list of machines in
$MachineList = Get-Content -Path c:\outdir\machinelist.txt;
foreach ($Machine in $MachineList){
($Machine + ": " + #(Get-WmiObject -ComputerName $Machine -Namespace root\cimv2 -Class Win32_ComputerSystem)[0].UserName) | Out-File "C:\outdir\result.txt" -Append
}
If you change the destination directory to somewhere that all computers have access to, it can run on multiple computers. It won't email it to you but you can just grab it.
You'll need to pipe those properties into the file like..
[System.Environment]::UserName, [System.Environment]::UserDomainName, [System.Environment]::MachineName | Out-File T:\Test.txt

PowerCLI: Task Automation

I have a script that I want to make automatically run every Monday and Thursday each week. I was curious how if it is possible to do this on PowerCLI or if I would have to create a .bat to accomplish this goal. I did some searching and learned that this piece of code was necessary in my script at the top of the line:
add-pssnapin VMware.VimAutomation.Core # <----------
$server = $args[0]
$date = get-date
new-snapshot -vm $server -name "Auto Created via Powershell" -description $date
get-snapshot -vm $server | sort -property created -desc | select -skip 6 | foreach-object{remove-snapshot $_ -confirm:$false}
What else would I need to get this code to run every Monday and Thursday?
Thanks!
EDIT: Where would I edit the task scheduler in order to allow this to run? I've provided an image of where I'm at (that and I'm also a visual person :P )
Why not just using the Task Scheduler of Windows to execute your script as:
powershell.exe -file yourscript.ps1
use powershell /? to kown more options