Custom PowerShell Label script - powershell

Asking for a bit of help with my script. I would like to get a list saved to a thumb drive with the computer name and the WAN address. I know I can add a custom label with the computer name but would get the default name. I already set the computer to change the name on reboot but I do not want to reboot as there are other things that need to happen before rebooting. The computers are new and are not added to the domain. I have a thumb drive that will auto-load and assist in changing the name without asking to reboot. So other software can install.
This is what I have so far:
getmac /v /FO CSV | ConvertFrom-Csv | Select-Object #{n='ComputerName';e={$env:COMPUTERNAME}},'Physical Address','Connection Name' | Where-Object { $_.'Connection Name' -Match 'Wi-Fi' }
And this is the output:
ComputerName Physical Address Connection Name
------------------ ------------------ --------------------
Desktop-9K293 XX-XX-XX-XX-XX Wi-Fi
I want the ComputerName to be the new name before rebooting. This way I can add an Export-CSV ~Location\MAC_Report.CSV -NoTypeInformation -append at the end of that code. Is there a way? Or do I need to restart the computer and generate that CSV using the same code?
I would love it to look:
ComputerName Physical Address Connection Name
------------------ ------------------ --------------------
NEW_____Name XX-XX-XX-XX-XX Wi-Fi
There are a lot of things I can make my thumb drive do. This way I have fewer restarts before adding the rest of the software(s) that also requires a restart. This way I cut my restart to one, on both all the software and computer rename.

I ended up just saving a TXT to the desktop of the computer, this way I can add the new computer name manually. This way I can then grab all the text files and consolidate them into one CSV or txt file. A bit of work but at least I can set the restart for later while I am able to install the rest of the software.
getmac /v /FO CSV | ConvertFrom-Csv | Select-Object 'Physical Address','Connection Name' | Where-Object { $_.'Connection Name' -Match 'Wi-Fi' } | Export-CSV -Path "$env:USERPROFILE\Desktop\WLAN_MAC.TXT" -NoTypeInformation
If there was a better way I would have done it.

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}

Generate a list of App Pool Virtual Path authentication settings using PowerShell?

I have been looking at all the PowerShell commands like Select-WebConfiguration, Get-WmiObject, Get-IISAppPool to generate a list of the enabled App Pool authentication settings for all the app pools on my servers. We have like 10 servers and a dozen+ app pools on each and want to find a quick way to check settings. Checked a lot on the web and haven't been able to find a command to generate a nice neat listing.
If you want to get the iis application pool identity then you could try the below command:
Import-Module WebAdministration;Get-ChildItem -Path IIS:\AppPools\ |
Select-Object name, #{e={$_.processModel.username};l="username"}, <##{e={$_.processModel.password};l="password"}, #> #{e={$_.processModel.identityType};l="identityType"} |
format-table -AutoSize
I was able to piece this together below and it seemed to work. Once last thing I am trying to figure out is how to use this same command to query remote servers
Get-WebConfiguration system.webServer/security/authentication/* -Recurse | where {$_.enabled -eq $true} | Sort-Object location,itemxpath | Select location,itemxpath,enabled | format-table -AutoSize
I found out that to run this command on another machine you use the command enter-pssession and the server name. It does not provide any switches that allow you to run them on another server.

Powershell - check for last time computers were restarted

I need to make sure all computers are being restarted at least once a week, and I've been googling on it, and I found something, but it's... rather something simple, something... 1-timer... What I want is to make it a bit more advanced.
Here's the command I found online:
Get-WmiObject Win32_OperatingSystem -ComputerName <computername> : select cname, #(LABEL='LastBootUpTime' ;EXPRESSION=($_.ConverttoDateTime($_.lastbootuptime)))
(I'm not sure if sharing the links is a good idea here, but I just googled for "check when remote computer was last restarted" and clicked on a link on enterprisedaddy)
I do not know anything about PowerShell, so I'm asking for your help. Also, it may be useful not only to me, but to others as well...
Here's what I want:
Create the *.ps1 file (I can do that) and make it run it 24/7
Instead of copying all computers each time, I want to append new computers to the list, because otherwise, the list would be very, very long... and I don't want to be deleting a whole bunch of computers and making sure only 1 copy is left and deleting all other every day...
Export the list into either *.txt or (even better) *.csv
At the end of the day, the *.ps1 would create a new *.txt or *.csv file and start it all over. In a new file. Of course leaving the old one (or all others, starting day 2...) for the review...
I understand there's very little hope, but if you can help me - great. If not - well, it may take forever to google for it all, but in the end, I may be able to find it all myself... Although there is even less hope here...
To be fair, all I need is to see the last time the computers were restarted, and that's all, so if you know of an easier way - I'm ready to read about other ideas.
This is not a full answer, but should help you toward your goal. If I'm interpreting your question correctly you want to check the last boot up time daily and report machines that haven't rebooted in the last 7 days. That data should then be stored in a csv file.
So this is actually quite easy to do, and PowerShell is a great place to do it. However, you have to "develop" on top of what you've already discovered. Set goals and meet those goals.
A start might be something like:
$Today = Get-Date
$ReportDate = $Today.AddDays( -7 )
$OutputCsv = ("C:\Temp\" + $Today.ToString( "yyyy-MM-dd" ) + ".csv" )
$BootTimes =
Get-WmiObject Win32_OperatingSystem -ComputerName pyex06 |
Select-Object PSComputerName, #{ LABEL='LastBootUpTime' ;EXPRESSION={ $_.ConverttoDateTime($_.lastbootuptime) } }
$BootTime |
Where-Object{ $_.LastBootUpTime -lt $ReportDate } |
Export-Csv -Path $OutputCsv -NoTypeInformation
Note: I didn't test this just hammered it out quickly for demonstration.
What's happening:
Get the current date.
Use the current date to calculate the date boundry earlier than which you want to report on.
Use the data again to derive a string suitable for naming a somewhat unique output file.
Do the query, add the LastBootUpTime property. Note: I made several syntax corrections there.
Now run the results through a Where{} statement that will filter for boot times more than 7 days old, and export to a CSV file.
Again this is just a start. You will need to add an ability to work against more than one computer, You'll need to think about what your input is going to be for that. You will probably also want to add error handling as WMI (and later CIM) connections can and do fail.
An aside: Get-WMIObject is deprecated. It's been replaced by Get-CimInstance. GetCimInstance will return a LastBootUpTime property as an actual date, with no need to add the property. That command would look something like?
Get-CimInstance Win32_OperatingSystem -ComputerName ComputerName |
Select-Object PSComputerName,LastBootUpTime
All of these things are very well documented. In fact I'm sure somebody has even published a script doing exactly what you want. You have to have some idea of how building a larger script will progress and hopefully I've given you that much. It's a series of solving individual issues and putting those solutions together etc.
BTW, the WMI stuff is depreciated, and CIM is the new hotness going forward. Note that win using cross-platform PowerShell (PowerShell Core), the WMI cmdlets do not exist.
$PSVersionTable.PSVersion
# Results
<#
Major Minor Build Revision
----- ----- ----- --------
5 1 19041 1
#>
(Get-Command -Name '*wmi*').Count
# Results
<#
21
#>
$PSVersionTable.PSVersion
# Results
<#
Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 0 3
#>
(Get-Command -Name '*wmi*').Count
# Results
<#
0
#>
Secondly, the command you posted is not syntactically correct and thus would never work.
Lastly, always do the basic stuff first to make sure you are getting what you'd expect before taking the next step.
Get-CimInstance -ClassName Win32_OperatingSystem |
Select-Object -Property '*'
# Results
<#
...
CSName : Lab01
...
Description :
InstallDate : 20-Jun-20 18:59:14
...
Distributed : False
LastBootUpTime : 13-Aug-20 01:00:42
LocalDateTime : 20-Aug-20 14:01:53
...
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
#>
Note, you can get the dates directly with no conversions needed, then format as needed.
Get-CimInstance -ClassName Win32_OperatingSystem |
Select-Object -Property CSName, LastBootUpTime,
#{
Name = 'TimeSpanSinceLastRestart'
Expression = {New-TimeSpan -Start $(Get-Date) -End $PSItem.LastBootUpTime }
}
# Results
<#
CSName LastBootUpTime TimeSpanSinceLastRestart
------ -------------- ------------------------
Lab01 13-Aug-20 01:00:45 -7.15:02:24.1130902
#>
As for this...
My question is how to make it run 24/7 and append new computer
... just put in in a scheduled task (on each host or on an admin workstation where you get computer names from AD or from a file) and export to either a CSV or a file using the -Append parameter.
(Get-ADComputer).Name |
ForEach{
Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $PSItem |
Select-Object -Property CSName, LastBootUpTime,
#{
Name = 'TimeSpanSinceLastRestart'
Expression = {New-TimeSpan -Start $(Get-Date) -End $PSItem.LastBootUpTime }
} |
Export-Csv -Path 'D:\Temp\SystemRebootReport.csv' -Append -NoTypeInformation -WhatIf
}
# Results
<#
What if: Performing the operation "Export-Csv" on target "D:\Temp\SystemRebootReport.csv".
#>
Just remove the -WhatIf to create the file.
Update
As for ...
[So how do I use this implicit remoting instead then?]
...this is all detailed in the Powershell Help files, see
about_Remote_Requirements - PowerShell | Microsoft Docs
'PowerShell implicit remoting active directory'
https://www.youtube.com/results?search_query=powershell+implicit+remoting+active+directory
https://www.itprotoday.com/powershell/powershell-implicit-remoting-never-install-module-again
TechNet Install RSAT for Windows 10 1809 and 1903 and 1909 -
automated

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

Get virtual SCSI hardware on servers using Powershell

I'm trying to use Powershell to get SCSI hardware from several virtual servers and get the operating system of each specific server. I've managed to get the specific SCSI hardware that I want to find with my code, however I'm unable to figure out how to properly get the operating system of each of the servers. Also, I'm trying to send all the data that I find into a csv log file, however I'm unsure of how you can make a powershell script create multiple columns.
Here is my code (almost works but something's wrong):
$log = "C:\Users\me\Documents\Scripts\ScsiLog.csv"
Get-VM | Foreach-Object {
$vm = $_
Get-ScsiController -VM $vm | Where-Object { $_.Type -eq "VirtualBusLogic" } | Foreach-Object {
get-VMGuest -VM $vm } | Foreach-Object{
Write-output $vm.Guest.VmName >> $log
}
}
I don't receive any errors when I run this code however whenever I run it I'm only getting the name of the servers and not the OS. Also I'm not sure what I need to do to make the OS appear in a different column from the name of the server in the csv log that I'm creating.
What do I need to change in my code to get the OS version of each virtual machine and output it in a different column in my csv log file?
get-vmguest returns a VMGuest object. Documented here: http://www.vmware.com/support/developer/PowerCLI/PowerCLI51/html/VMGuest.html. The documentation is sparse, but I would guess the OSFullName field would give you the OS version. So you could change the write-output line to
add-content $log "$($vm.guest.vmname) , $($vmguest.guest.OSFullName)"
and you'd be on the right track. The comma in the output is what makes the output "comma separated values". A CSV file can optionally have a header. (See Import-CSV / Export-CSV help for details). So you might want to add the following as the second line of your script:
add-content $log "VM Name, OS Name" # add CSV header line