Sending PowerShell output to a sub directory - powershell

I have a script that is generating multiple CSV files with the time stamp and group name as part of the file name. Right now the script outputs the CSV files into the directory the script is run from.
I would like to have the CSV files output to a sub directory. Whenever I include a path in my Export-Csv command, I get an error.
Here is what I have:
#This array lists the names of the AD groups that the script will query to enumerate membership.
$aGroups = #("Group1", "Group2")
#Create a log file to verify that the script did not have any errors.
$strTimestamp = [string](Get-Date -Format "yyyy-MM-dd_hh-mm")
Start-Transcript ADGroupScriptLog-$strTimestamp.txt
Write "Enumerating group membership. This may take some time..."
#Loop through each group in the array and output to CSV each member in the group.
foreach ($group in $aGroups) {
Get-QADGroupMember $group -Indirect -Type 'user' -ShowProgress -ProgressThreshold 0 -Sizelimit '0' |
Select-Object Name, SAMAccountName, givenName, sn, title, manager, Description |
Export-Csv ($strTimestamp + "_" + $group + ".csv") -NoType
}
Write "Execution Complete"
Get-Date -format s
Stop-Transcript
I have tried:
Export-Csv \\Server\Share\File.csv ($strTimestamp + "_" + $group + ".csv") -NoType
**********************
Windows PowerShell transcript start
Start time: 20180207113151
Username :
Machine : (Microsoft Windows NT 6.1.7601 Service Pack 1)
**********************
Transcript started, output file is OneSourceUsers-2018-02-07_11-31.txt Enumerating group membership. This may take some time...
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"2018-02-07_11-31_OneSrce_BI_Browser.csv" to type "System.Char". Error:
"String must be exactly one character long."
At E:\OneSource\get_OneSourceUsers.ps1:19 char:215
+ ... neSource\Output($strTimestamp + "_" + $group + ".csv") -NoType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ExportCsvCommand
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"2018-02-07_11-31_OneSrce_BI_Admin.csv" to type "System.Char". Error:
"String must be exactly one character long."
At E:\OneSource\get_OneSourceUsers.ps1:19 char:215
+ ... neSource\Output($strTimestamp + "_" + $group + ".csv") -NoType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ExportCsvCommand
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"2018-02-07_11-31_OneSource MSSQL POC.csv" to type "System.Char".
Error: "String must be exactly one character long."
At E:\OneSource\get_OneSourceUsers.ps1:19 char:215
+ ... neSource\Output($strTimestamp + "_" + $group + ".csv") -NoType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ExportCsvCommand
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"2018-02-07_11-31_One Source Reporting Alert.csv" to type "System.Char".
Error: "String must be exactly one character long."
At E:\OneSource\get_OneSourceUsers.ps1:19 char:215
+ ... neSource\Output($strTimestamp + "_" + $group + ".csv") -NoType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ExportCsvCommand
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"2018-02-07_11-31_One Source Loads.csv" to type "System.Char". Error:
"String must be exactly one character long."
At E:\OneSource\get_OneSourceUsers.ps1:19 char:215
+ ... neSource\Output($strTimestamp + "_" + $group + ".csv") -NoType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ExportCsvCommand
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"2018-02-07_11-31_One Sales Team.csv" to type "System.Char". Error:
"String must be exactly one character long."
At E:\OneSource\get_OneSourceUsers.ps1:19 char:215
+ ... neSource\Output($strTimestamp + "_" + $group + ".csv") -NoType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ExportCsvCommand
Export-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value
"2018-02-07_11-31_OneSrce_BI_Contributor.csv" to type "System.Char".
Error: "String must be exactly one character long."
At E:\OneSource\get_OneSourceUsers.ps1:19 char:215
+ ... neSource\Output($strTimestamp + "_" + $group + ".csv") -NoType
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ExportCsvCommand
Execution Complete 2018-02-07T11:31:51
**********************
Windows PowerShell transcript end
End time: 20180207113151
**********************

When you run something like
... | Export-Csv \\server\share($strTimestamp + "_" + $group + ".csv") -NoType
PowerShell sees \\server\share as one argument, and ("something" + ".csv") as another argument (due to the grouping expression). The second positional parameter is passed to the parameter -Delimiter, which expects a single character. Hence the error you observed.
To create a path string from several variables just use a string with nested variables:
... | Export-Csv "\\server\share\${strTimestamp}_${group}.csv" -NoType

Related

Cannot convert value to type "System.Int32"

I'm trying to import a csv file and select only columns where the number is above the a certain value (80):
import-csv 'C:\temp\t\xxxx.csv' | where-object {[int]$_.utilization -gt 80}
The error I'm getting is:
Cannot convert value "17 %" to type "System.Int32". Error: "Input string was not in a correct format."
At line:57 char:22
+ import-csv 'C:\temp\t\xxxx.csv' | where-object {[int]$_.utilization -gt 80}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
$_utilization seems to be an Object
Any thoughts?
I tried to convert with $util = [int]$_.utilization, but I get the following error:
Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".
At line:3 char:1
+ $util = [int]$_.utilization
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
$_.utilization contains a string. To parse the numeric prefix as an integer, remove the space and percentage sign from the string first:
[int]($_.utilization -replace ' %$') -gt 80

Update multiple users

I am trying to simultaneously update some users in my AD, but not being able to generate the script correctly. I am working with .csv and I get errors!
script
Import-Csv -Path C:\Temp\userteste3.csv | foreach-Object {Set-ADUser -Identity $_.SamAccountName -Add #{-telephoneNumber $_.telephoneNumber;-OtherPhone $_.OtherPhone;ipPhone $_.ipPhone}}
csv
error
No linha:1 caractere:105
+ ... oreach-Object {Set-ADUser -Identity $_.SamAccountName -Add #{-telepho ...
+ ~
O literal de hash estava incompleto.
No linha:1 caractere:186
+ ... ber $_.telephoneNumber;-OtherPhone $_.OtherPhone;ipPhone $_.ipPhone}}
+ ~
Token '}' inesperado na expressão ou instrução.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : IncompleteHashLiteral

Bulk Add SmtpAddress to users Exchange 2010

We just recently added a domain to our accepted domains and e-mail address policy. While many of our users follow that policy, we have a third domain that some users have as their primary address that does not follow an address policy. I need to take those users and add an SMTP Address in the format of firstname.lastname#domain2.com.
E.g., john.doe#domain3.com (primary) has john.doe#domain1.com as an alias and needs to have john.doe#domain2.com added as an SMTP Address.
I have the following code but am receiving errors:
$Users = Get-Mailbox -ResultSize Unlimited | Where-Object {($_.PrimarySMTPAddress -like "*domain3.com*)}
foreach ($a in $Users) {
$b = Get-User $a.Primary.SMTPAddress
$a.EmailAddresses.Add("$($b.Firstname + "." + $b.Lastname)#domain2.com")
}
$Users |%{Set-Mailbox $_.PrimarySMTPAddress -EmailAddresses $_.EmailAddresses
Errors are as follows:
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "john.doe#domain3.com" value of type "Microsoft.Exchange.Data.SmtpAddress" to type "Microsoft.Exchange.Configuration.Tasks.UserIdParameter".
+ CategoryInfo : InvalidData: (:) [Get-User], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-User
Exception calling "Add" with "1" argument(s): "The address '.#domain2.com' is invalid: ".#domain2.com" isn't a valid SMTP address. The domain name can't contain spaces and it has to have a prefix and a suffix, such as example.com."
At C:\_scripts\SmtpAdd.ps1:4 char:23
+ $a.emailaddresses.Add <<<< ("$($b.Firstname + "." + $b.LastName)#domain2.com")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Cannot process argument transformation on parameter 'Identity'. Cannot convert the "john.due#domain3.com" value of type "Microsoft.Exchange.Data.SmtpAddress" to type "Microsoft.Exchange.Configuration.Tasks.MailboxIdParameter".
+ CategoryInfo : InvalidData: (:) [Set-Mailbox], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-Mailbox
Thanks
I think the problem starts with this line:
$b = Get-User $a.Primary.SMTPAddress
Get-User fails to return a valid user as $a.Primary.SMTPAddress doesn't return a type that Get-User can use. That then causes EmailAddresses.Add to fail as $b is null. Set-Mailbox fails for the same reason as Get-User
Try this instead (you'll also need to do this on the Set-Mailbox line):
$b = Get-User $a.Primary.SMTPAddress.ToString()

Split Select-String

Given this variable
$foo = help | Select-String powershell
Trying a split will fail
PS > $foo.split()
Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo]
does not contain a method named 'split'.
At line:1 char:1
+ $foo.split()
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
How can I split this variable?
The string value of the matched line is in the Line property of the MatchInfo object.
$foo.Line.split()
Split is a String method, so it must be called on a string.
[string] $foo = help | Select-String powershell
Or
$foo = help | Select-String powershell | Out-String

Convert accountExpires to DateTime in powershell commandline (last step, help needed)

I have the following piece of code that works fine to output the user's displayname and the accountExpires attribute from AD. I am running them on commandline because of restricted mode at work:
$objSearch.findall() | %{" " + $_.properties.displayname + "| " + $_.properties.accountexpires}
Now I need to convert this output, specifically the accountExpires attribute to a humanly readable date.
After googling I figured that I can use something like the below to convert between the accountExpires and a datetime.
[datetime]::fromfiletime(129138320987173880)
But I am having issues combining the two. I tried the following:
$objSearch.findall() | %{" "+ $_.properties.displayname + " " + [datetime]::fromfiletime($_.properties.accountexpires)}
Cannot convert argument "0", with value: "System.DirectoryServices.ResultPropertyValueCollection", for "FromFileTime" to type "System.Int64": "Cannot convert the "System.DirectoryServices.ResultPropertyValueCollection" value of type "System.DirectoryServices.ResultPropertyValueCollection" to type "System.Int64"."
At line:1 char:96
+ $objSearch.findall() | %{" "+ $.properties.displayname + " " + [datetime]::fromfiletime <<<< ($.properties.accountexpires)}
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
$objSearch.findall() | %{" "+ $_.properties.displayname + " " + [datetime]::fromfiletime $_.properties.accountexpires}
Unexpected token '' in expression or statement.
At line:1 char:99
+ $objSearch.findall() | %{"This is "+ $.properties.displayname + " " + [datetime]::fromfiletime $_ <<<< .properties.accountexpires}
+ CategoryInfo : ParserError: (_:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
How can I convert the accountExpires to a humanly readable date?
You just miss that the underlying ADSI COM object presents properties as arrays here is a way to get the accountexpires property, just use $_.properties.accountexpires[0].
$search = [ADSISearcher]"OU=MonOu,DC=dom,DC=fr"
$search.Filter = "(cn=Jean Paul Blanc)"
$user = $search.FindOne()
$user | %{" "+ $_.properties.displayname + " " + [datetime]::fromfiletime($_.properties.accountexpires[0])}
This give for me :
Jean Paul Blanc 12/07/2012 00:00:00