I read a lot of articles, but now i'm kinda stuck. I use this code to extract all the databases from a sql server and the size & freespace available.
So far ok. Now I want to convert the txt to a csv so i can open it in excel. The problem is it opens in excel only in one collumn instead of 3 (Name, size, freespace). How must I edit this code so it will open in 3 collumns instead of one?
The layout of the txt file is something like this: "Name" whitespace "Size" whitespace "Free_Size(MB" |
from txt file to csv and open in multi collumns using powershell
Register-PSSessionConfiguration error
Hi everyone,
I didn't know where I could put an helping solution for someone would have this issue because I found it by myself. So maybe it could help.
Case:
There may be a case where you have a user account that doesn’t need to have Administrator rights on a server, but the user still needs to run a command to pull some information. The problem is that I do not want to give the user complete access to my remote system.
Solution/Problem:
- Create a dedicated user who will be a local administrator of the target computer.
- Jump on the target computer and open powershell with priviledges.
- Type this command :
Register-PSSessionConfiguration -Name <nameofthesession> -RunAsCredential <domain\<dedicateduser> -Force
e.g. Register-PSSessionConfiguration -Name PowerShell.DHCP.Session -RunAsCredential 'CL_095\s-dhcp' -Force
Normally you should have :
WARNING: When RunAs is enabled in a Windows PowerShell session configuration, the Windows security model cannot enforce
a security boundary between different user sessions that are created by using this endpoint. Verify that the Windows
PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities.
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin
Type Keys Name
---- ---- ----
Container {Name=PowerShell.DHCP.Session} PowerShell.DHCP.Session
But if you have :
WARNING: When RunAs is enabled in a Windows PowerShell session configuration, the Windows security model cannot enforce
a security boundary between different user sessions that are created by using this endpoint. Verify that the Windows
PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities.
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin
Type Keys Name
---- ---- ----
Container {Name=PowerShell.DHCP.Session} PowerShell.DHCP.Session
Register-PSSessionConfiguration : The verification of the runAs user credentials failed with the error -2146892994
At line:263 char:5
+ Register-PSSessionConfiguration -filepath $arg[0] -pluginName $a ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo :NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId :Microsoft.PowerShell.Commands.WriteErrorException,Register-PSSessionConfiguration
You should probably have a 300 event id in your eventviewer, too.
Resolution:
In my case, the reason was I didn't want the user to have the possibility to make an interactive logon with the dedicated account. To do that, I ticked the checkbox "Smart Card for interactive logon" in the Active Directory. But when the Register-PSSession cmdlet try to register a configuration, it try to authenticate BUT I checked the smard card so it was normal it was impossible for the cmdlet to make this operation.
Before finding the solution I tried to make a "check password" with tools. You will probably have "invalid password". It is a misleading error. This is not the right error.
I hope I could help someone,
Kind Regards,
Arnaud
PowerShell Bug in Test for True?
Good Afternoon,
I tried to put this through Connect, but it seemed unhappy about my attempts to get to the PowerShell listing. So I thought I might post this here. In a script I am testing for a returned WMI value that may or may not be $True. I test for the value of $True and then against "Other Value That Doesn't Matter". As I was running some tests, I noticed that if the returned value from WMI that I was testing was $True, the test against "Other Value that Doesn't Matter" returned a test response of $True.
So I ran a few more tests with explicit $True value in the test to confirm it wasn't something in my WMI return causing the oddity:
PS C:\Users\THISISME> if($True -eq "Blah"){write-host "This should not be"}
This should not be
PS C:\Users\THISISME> if($True -eq $False){write-host "This should not be"}
PS C:\Users\THISISME> if($True -eq 42){write-host "This should not be"}
This should not be
PS C:\Users\THISISME> if($True -eq $True){write-host "This should be"}
This should be
PS C:\Users\THISISME> if($False -eq "Blah"){write-host "This should not be"}
PS C:\Users\THISISME> if($False -eq $True){write-host "This should not be"}
PS C:\Users\THISISME> if($False -eq 42){write-host "This should not be"}
PS C:\Users\THISISME> if($False -eq $False){write-host "This should be"}
This should be
As you can see, if you test the value $True against anything EXCEPT $False, it returns that yes, they are indeed equal and returns $True. This is not the same if you test $False against other values. I also tested the same values in reverse, and got the results one would expect: 1/$True/True -eq $True but other values do not.
I have included my PS Version information below (via get-host) for all version of PowerShell that I have tested on: 5.1.14393.576 and 4.0
I tend to think that this isn't by design, but I've been wrong before so I thought I'd ask.
Thanks!
JT Howard
Senior Consultant | Sogeti USA
Filtering Null $_.GivenName accounts
$properties = @( @{ N = 'First Name'; E = { $_.GivenName } }, 'Initials', @{ N = 'Last Name'; E = { $_.surname } }, @{ N = 'Username'; E = { $_.Samaccountname } }, @{ N = 'Email Address'; E = { $_.emailaddress } }, @{ N = 'Office ID'; E = { $_.physicaldeliveryofficename } }, @{ N = 'Office Phone'; E = { $_.telephonenumber } }, @{ N = 'Password Last Set'; E = { $_.PasswordLastSet } }, @{ N = 'Locked Out'; E = { $_.LockedOut } }, @{ N = 'Expiration Date'; E = { (Get-Date $_.PasswordLastSet).AddDays($maxPassAge) } }, @{ N = 'PasswordLifeLeft'; E = { if ($_.PasswordExpired) { 0 } Else { $maxPassAge - ((Get-Date) - $_.PasswordLastSet).Days } } }, 'Description' @{ N = 'Group Membership'; E = {($_.MemberOf | % { Get-ADGroup $_ | Select -ExpandProperty Name} | Sort) -join ', '}} ) $userproperties='physicaldeliveryofficename,telephonenumber,emailaddress,initials,description,passwordlastset,lockedout,PasswordExpired,memberof' -split ',' $ouList | ForEach { Get-ADUser -Filter * -properties $userproperties -SearchBase $_ } | Sort-Object -Unique | Select $propertiesIs there a certain change to the givenname expression that will exclude the blank results
Get-MsolUser Returns All Results as True
I'm attempting to find a list of all students who have a license for Yammer.
Get-MsolUser -All -Title Student | Where-Object {$_.isLicensed -eq $true -and $_.Licenses.ServiceStatus[2].ProvisioningStatus -ne "Disabled"}
This returns thousands of results with the value True for all. Yet, when I check the admin center most of the results do not have access to yammer. What do I need to modify or add in order to receive a list of users who actually have the license?
Thank you!
(SO) Regular expression ... weirdly! (very, indeed)
As you can see here, http://bit.ly/2jxiNky people like to complicate what is, naturally, simple.
▪
Date of most recently installed update
Hi All,
I'm looking for a PowerShell script that help me manage my Windows servers who receive updates from our internal WSUS server. We are using WSUS 3.0 running on a single Windows 2012 R2 machine.
In simple terms, I need a PowerShell script that can produce a simple table showing the following:
- The date of the most recently installed update for each server
- Email these results to a specified email address.
I am not interested inwhich update was installed – I am only concerned about when the last update was installed on each server.
I have seen a very good script posted by Aman Dhally on his IT blog, the script does exactly what I need (minus the emailing part), but it only returns results for the machine where the script is run from, here is the script:
First enter:
$windowsUpdateObject=New-Object-ComObject Microsoft.Update.AutoUpdate
Then enter:
$windowsUpdateObject.Results
This produces a very simple table showing the date of the last successful update that was installed.
(to my frustration I cannot post URL's or images of the result, as my account has yet to be verified!)
What I would like is for the above to query a list of my Servers and produce the results exactly in the same way as above, one line per server. So column 1 =computername, column 2=LastSearchSuccessDate, column 3=LastInstallationSuccessDate
For example, I have a text file: C:\Computers.txt, which contains a list of all my Windows Servers. Would it be feasible to produce a script that could say get-content c:\Computers.txt and for each computer listed, show me the date of the most recent Windows Update that was installed?
I hope this makes sense, I’d be grateful for any assistance. I should add that I’m a PowerShell newbie, so there is still a lot to learn for me.
Many thanks
Emails sent report - Exclude self domain
Hi All,
can anyone help me with generating emails sent report by user ? but report should not include self domain.
example : suppose my id is atul@abcd.com so if I am generating report for myself then that report should not list other ids of abcd.com it should show only external ids and not my own domains mail ids
I am running below command , but not helping - it is listing other ids of abcd.com (internal communication)
Get-TransportServer | Get-MessageTrackingLog -ResultSize Unlimited -sender: atul@abcd.com -Start "12/01/2016" -End "12/31/2016"| Select timestamp,EventID,Recipients,MessageSubject >C:\EmailStat_Report\atul.csv
-Atul
TheAtulA
Renaming a computer takes it out of domain
Hi,
I use a powershell script to rename our domain computers, it's just:
Rename-Computer -NewName $computername -DomainCredential $mycreds -Force -PassThru
90% of the time works, but in some cases, after launching this script and restarting the computer, the computer is out of domain.
The script also searches AD and makes sure that the new hostname isn't on AD.
What I've seen:
- c:\windows\debug\netsetup.log tells that everything had gone ok.
- The object exists on AD and it's renamed (same OU)
- When this happens, if I try to log on to computer with an user domain, appears the error "The trust relationship between this workstation and the primary Domain failed"
Any idea of where is the error and how can I control it on future renames?
Thanks
Run Powershell script as Scheduled task, that uses Excel COM object
What am I missing here..
I have Powershell script that uses the Quest AD cmdlets to get computer information from AD and populate an Excel spreadsheet with the data.
The script works fine, so I created a batch file and started the script from there (which works fine as well). It populates the excel spreadsheet, saves and closes the file.
If I run the script as a scheduled task, I can see from the logging that it supposedly gets the computers from AD, and runs through them. But a file is never saved, I have tried to run the scheduled task with admin credentials.
What am I forgetting?
Powershell secure string to string
Hi to all
at first I know that saving a Password in a string is not good.
I have to do this, couse I am Aiming for an system that does not recognise Secure Strings and cant handle them.
so i need to convert a secure string to a normal String.
I looked for it in different Forums but cant find a solution.
here is my code so far
$Credentials = Get-Credential
[string]$PlainPassword = $Credentials.GetNetworkCredential().Password.ToString()
but when I now try to give $Plainpassword to a function, it tells my that it cant convert to string.
Get-Type $PlainPassword
is not giving any answer.
If there is no way to do what I wanted, is there maybe a possibility to " read-host " something hidden and get it as string in my code ?
I hope you can help me out and Thanks for any answer
Powershell - Running an Msi on a remote computer
What im doing is writing a script which takes the size of an MSI file via its -FilePath and then compares it to the C:\ Drive to see if there is enough space to install. I have also added the Parameter -ComputerName which enables me to compare the size of the MSI file against the C:\ Drive on a remote computer..
I've now added to this script so the user has the option not only to check if they have enough storage to install but to actually go ahead with the install.. To do this I've ran Start-Process $FilePath which runs the installation wizard for the MSI.. I've added /Quiet to this so there is no user interaction it just does it..
Only thing is - When I do this, it will run the installation for the MSI on the local machine regardless if I've checked the storage on a remote machine.. How can I link the check with the install so if I check a remote machine it will copy the MSI file to the remote machine before running so the MSI is installed on the remote machine.
If someone can point me in the right direction id be most grateful..
Thanks
#P.S - Apologies, I know It looks like a longwinded explanation to quite a short query..
Formatting gets wonky when using add-content before out-file
PS novice here. Server is running PS v4.
I'm trying to get a simple list of members in a group to a text file with the proper headings. When I run this -
add-content -path c:\temp\text.txt -value "Administrators"
...I get the expected result (a text file with "Administrators" printed at the top)
When I run this -
get-adgroupmember administrators|select name|outfile c:\temp\text.txt -append
...I get the expected result (a file with the groups members formatted neatly down the left with the heading "name"
However, when I run this -
add-content -path c:\temp\text.txt -value "Administrators";get-adgroupmember administrators|select name|outfile c:\temp\text.txt -append
...I get "Administrators" printed across the top but the group members that were previously formatted neatly down the left side are instead printed straight across a single line (including the 'name' heading) with spaces between each character and about a hundred spaces between each entry.
e.g. instead of this -
Administrators
name
------
person1
person2
person3
...I get this
Administrators
n a m e - - - - - p e r s o n 1 p e r s o n 2 p
e r s o n 3
...all on one line
Any ideas how to fix and what is causing this? I know this can be done a half dozen different ways but I'd like to figure out why the output is formatting the way it is.
TIA!
Powershell Exchange 2007 Distribution lists
Need to know powershell command(s) to run to query exchange 2007 for all distribution groups with the name "DL_Stores".
Also want to only include the following, as I'm trying to assess what is or isn't enabled:
AcceptMessagesOnlyFrom
AcceptMessagesOnlyFromDLMembers
RejectMessagesFrom
RejectMessagesFromDLMembers
RequireSenderAuthenticationEnabled
Also need to know command or filter to see where named accounts are nested also please.
foreach pass varible data to export-csv
I want to pass the data I'm testing in each foreach to the record collection of export-csv.
Example:
ForEach ($Zone in $Zones) {
$Results = $Zone | Get-DnsServerResourceRecord -ComputerName $DNSServer | select hostname,recordType,zonename -expand recorddata
$Results | export-csv -path "C:\Users\jlawson23\Desktop\LOGIN_$($Zone.ZoneName)_DNSOUT$CurrentDate.csv"
}
So for zone1 I would get
zonename1, hostsname, recordtype, recorddata
for zone2 I would get
zonename2, hostsname, recordtype, recorddata
foreach pass collect all data to one export-csv command
I want to collect the data in each foreach to the full record collection of one export-csv.
Example code where i get a single file for each zone.
ForEach ($Zone in $Zones) {
$Results = $Zone | Get-DnsServerResourceRecord -ComputerName $DNSServer | select hostname,recordType,zonename -expand recorddata
$Results | export-csv -path "C:\Users\jlawson23\Desktop\LOGIN_$($Zone.ZoneName)_DNSOUT$CurrentDate.csv"
}
So for zone1 I would get file 1
hostsname, recordtype, recorddata
for zone2 I would get file 2
hostsname, recordtype, recorddata
Now I would like to get one file only with all zones data.
I tried moving this command out of the function but only get the last loop result:
$Results | export-csv -path "C:\Users\jlawson23\Desktop\LOGIN_$($Zone.ZoneName)_DNSOUT$CurrentDate.csv"
Create new Web App Deployment type using Set-CMWebApplicationDeploymentType
I'm attempting to load a list of WebApps into SCCM 2012 R2 with PowerShell. I know how to create the applications, but when it comes to adding the deployment type, I'm encountering an issue I can't seem to get around:
Rough example:
$AppName = "Google:
$DepType = "Google -WebApp"
set-location PRI:
Set-CMWebApplicationDeploymentType-ApplicationName$Appname-DeploymentTypeName$DepType-URL"http://www.google.ca"
and get this:
Set-CMWebApplicationDeploymentType : No object corresponds to the specified parameters.
At C:\Temp\AddWebApps-SF.ps1:13 char:1
+ Set-CMWebApplicationDeploymentType -ApplicationName $Appname -DeploymentTypeName ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Microsoft.Confi...mentTypeCommand:SetWebApplicationDeploymentTypeCommand) [Set-CMWebApplicationDeploymentType], ItemNotFoundException
+ FullyQualifiedErrorId : ItemNotFound,Microsoft.ConfigurationManagement.Cmdlets.AppMan.Commands.SetWebApplicationDeploymentTypeCommand
Where do I go from here?
Scott
error on get-help get-service -showwindow
At line:1 char:33
+ get-help get-service -showwindow <<<<
+ CategoryInfo : InvalidArgument: (:) [Get-Help], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetHelpCommand
Unable to access Sent folder using MAPI
I am using following script to access delegate users mail box but unable to access Sent folder. It is throwing following error
Exception calling "GetInbox" with "1" argument(s): "Sorry, something went wrong. You may want to try again."
$class =@"
using Microsoft.Office.Interop.Outlook; public class MyOL{ public MAPIFolder GetInbox(string userName){ Application oOutlook = new Application(); NameSpace oNs = oOutlook.GetNamespace("MAPI"); Recipient oRep = oNs.CreateRecipient(userName); MAPIFolder inbox = oNs.GetSharedDefaultFolder(oRep, OlDefaultFolders.olFolderSentMail); return inbox; } }"@Add-Type-AssemblyNameMicrosoft.Office.Interop.OutlookAdd-Type $class -ReferencedAssembliesMicrosoft.Office.Interop.Outlook $MyOL =New-ObjectMyOL $olInbox = $MyOL.GetInbox('otherUserName')
RaghuM
What version of WMF am i running
Hi all. I have a 2012 R2 Datacenter VM in my lab.
I want to install WMF V5 so that I can do a MVA course on line however when I try to install WMF 5 I get a generic answer saying it is not for this machine. I realise the response could be due to the component already being stalled by what I like to do is run a command and have it tell me whet version is installed. Is this possible?
I have run $PSVersionTable
Which returned:
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.34014
BuildVersion 6.3.9600.17400
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
Is either of those WMF by chance?
Thank you for looking