Assistance with PS script - powershell-4.0

the below script works perfectly, however, I need to add the EmailAddress attribute and include the email addresses in the CSV output, but all my attempts have failed. Please help as a far from an expert PS scripter.
Get-ADUser -Properties Description -Filter 'Description -like "the"' | Select Name,SamAccountName,Description | Export-Csv -path C:\temp\temp-users2.csv -NoTypeInformation

Related

I'm a novice at Powershell and im trying to complete a task

I'm starting to work with Powershell and I've been doing some courses online. At this moment I'm stuck in a Challenge, I hope some good soul can help me with the instructions from the course.
Instructions are:
1-Find out what Windows features are installed on the server machine. (I'm remoting command to a computer named "Server")
2-Select only the data stored in the Name and InstallState columns.
3-Sort the data by the Name property in ascending (alphabetical) order.
4-Make sure the output format is set to table
5-Save the final output into a file called C:\features.txt on your desktop machine.
What I have come up with is this:
Invoke-Command -ComputerName Server -ScriptBlock{
>> Get-WindowsFeature | Select-Object -Property Name, InstallState | Sort-Object -Property Name | Format-Table
>> } | Out-File C:\features.txt
I have tried both with and without the select-object command since I know the format-table command works almost the same in this case. Thank u!
When ever I invoke a scriptblock on a remote computer i assign it to a variable and then handle the results this:
$myResults= Invoke-Command -ComputerName Server -ScriptBlock{…}
Foreach ($item in $myResults){
Write-host” $item.name /
$item.nstallState”
}
You use the pipeline rather excessively which is not wrong but for me personally still a beginner my self it is not easy to totally comprehend what each of them is exactly returning and forwarding to the next. Dont try to write a perfect line with several pips in the first attempt. Start with the smallest fastest fraction of the task. In this case yust get them all out without filter and pipelines. Then work your way from there, make little changes, use write-host to display the results and trail and error yourself to a deeper understanding of each of them. And then in the end u can chain them up.
As per my comment for example.
# 1-Find out what Windows features are installed on the server machine.
Get-WindowsFeature
# Results
<#
#>
# 2-Select only the data stored in the Name and InstallState columns.
Get-WindowsFeature |
Select-Object -Property Name, InstallState
# Results
<#
#>
# 3 - Sort the data by the Name property in ascending (alphabetical) order.
Get-WindowsFeature |
Select-Object -Property Name, InstallState |
Sort-Object -Property Name
# Results
<#
#>
# 4-Make sure the output format is set to table
Get-WindowsFeature |
Select-Object -Property Name, InstallState |
Sort-Object -Property Name |
Format-Table # though this is not needed, since table is the default for less than 5 properties.
# Results
<#
#>
<#
# 5-Save the final output into a file called C:\features.txt on your desktop
machine.
#>
Get-WindowsFeature |
Select-Object -Property Name, InstallState |
Sort-Object -Property Name |
Export-Csv -Path 'SomePathName' -NoTypeInformation -Append
# (I'm remoting command to a computer named "Server")
$Computers |
ForEach-Object {
Invoke-Command -ComputerName $PSItem.ComputerName -ScriptBlock{
Get-WindowsFeature |
Select-Object -Property Name, InstallState |
Sort-Object -Property Name |
Export-Csv -Path 'SomePathName' -NoTypeInformation -Append
}
}

Powershell script CPU usage high

I've got a simple script that looks for a file across a bunch of servers. Issue is that on each server it is pegging CPU and causing issues for production workloads. How can I get this script to not DDoS my machines?!
Start-transcript C:\tools\Querylog.txt
$Servers = Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} -Properties OperatingSystem
Invoke-command -ComputerName $Server-ScriptBlock {Get-ChildItem -Path $_.Root -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*somefile-readme*' } |Out-File -FilePath <filePath>\results.txt -Append}
Stop-Transcript
Use the -Filter option with Get-ChildItem, it should be much more performant than returning all objects and filtering with Where-Object.
Also, not related to your CPU issue but in how you are crafting your Get-ADComputer call, you should use a String, not a ScriptBlock for the -Filter arguments on these cmdlets. From that answer:
-Filter doesn't support ScriptBlocks, but they Kind of Work Sometimes™ because they get ToString'd before getting evaluated. They will technically work if you use simple variable expansion like $_ or $emailAddress, but it will eventually cause you a headache, especially if you try to access an object property (like above) because it simply won't work. Use a string filter every time, and if you need to use an object property as a filter parameter, use Variable Substitution or Command Substitution.

wmic dont likes the variable im using

I made this code to kill a task. With Get-VBRJob i get all the backup jobs and their ID, then I isolate the job name imput, then filter just leave the ID and last it delete the header. This variable result is not working on the wmic command im using. I guess i need to convert the variable content in something?. Thanks!
$JobName = Read-Host "Enter Job name"
$JobID = Get-VBRJob | select name, ID | Where {$_.name -like $JobName} | select ID | Format-Table -HideTableHeaders
wmic Path win32_process Where "CommandLine Like '%$JobID%'" Call Terminate
It looks like there's blank lines above and below the id. I think you want
| select -expand id
instead with no format-table. And the id must appear in the commandline. You wouldn't normally store format-table output to a variable.
Btw, instead of wmic, you can use
get-wmiobject win32_process | where commandline -match $jobid | remove-wmiobject

powershell scheduled task caller

I have several hundred scheduled tasks. Im looking for a way to get the name of the task that called a powershell script when the script has been executed by the task scheduler. So for instance I could include that name in an alert I am sending so we know not only which server but which specific task
You can use the get-scheduledtask cmdlet. You find this cmdlet in the ScheduledTasks module.
Each returned task has an Actions Property.
E.g.
(Get-ScheduledTask)[0].Actions
To add on to Peter Schneider helpful answer which will give you details on the first task in the list. So, more specifically, to get them all, try this...
(((Get-ScheduledTask).Actions) | Select-Object *) -match 'powershell' | Select-Object -Property Id,Execute,Arguments | Format-Table -Wrap
Id Execute Arguments
-- ------- ---------
StartPowerShellJob powershell.exe -NoLogo -NonInteractive -WindowStyle Hidden -Command "Import-Module PSScheduledJob; …
Note, the '*' gest all properties and you may not want to do that, so, just explicitly select the ones you'd want
(((Get-ScheduledTask).Actions) | Select-Object -Property Id,Execute,Arguments) -match 'powershell' | Format-Table -Wrap

Grab the latest volume using PowerShell

I'm struggling trying to grab the latest volume/Drive using PowerShell
I have a result of a PowerShell look like this
PS C:\Users\me> Get-WMIObject Win32_Volume | select Name
Name
----
C:\
D:\
E:\
\\?\Volume{021a6bbd-0b97-4973-824a-7c635e362f09}\
\\?\Volume{bae1c1d6-59c3-44b1-9360-b7d3101c0e92}\
PS C:\Users\me>
If I want to access just this
E:
How can I filter out to :\ with the highest alphabetical order ?
I've been trying so many options using Select-String, but seems to get worse result.
The ones you want don't start with "\\". The drive letters may be returned in any order, so you need to sort them and take the last one:
Get-WMIObject Win32_Volume | Where-Object {$_.Name -NotLike '\\*'} | select Name | Sort-Object -Property Name | Select-Object -Last 1
Or, if the drive letter is known to be in the range A to Z, then it would be more sensible to use -Like '[A-Z]*' instead of -NotLike '\\*'.
Try something like this
Get-WMIObject Win32_Volume | where {$_.Name -eq "E:\"}
this should give you a list of objects wich you can access like an array. Also there is a lot of useful information here https://technet.microsoft.com/en-gb/library/2007.04.powershell.aspx

Resources