Substring Function don't work with a variable - powershell

I need the first 3 bytes of a string. My code gets an error.
# This Code don't work
$folderoutput="Z:\Home\Chronos\" + $datum.Month;
$test = Get-ChildItem -Path $folderinput| select name, state -last 1
$test.Substring(0,3)
# This Code work
$folderoutput="Z:\Home\Chronos\" + "11"
$test = Get-ChildItem -Path $folderinput| select name, state -last 1
$test.Substring(0,3)
Error:
Method invocation failed because [Selected.System.IO.FileInfo] does
not contain a method named 'Substring'. At Z:\skript\uebung1.ps1:16
char:1
+ $test.Substring(0,3)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Substring:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
What is the reason for the error?

Your $test variable references not a String but an object composed from the Name and State properties of the returned FileInfo instance. There is no Substring method on this composed object (nor on a FileInfo, for that matter), hence the error. To get the name of the file you need to access the Name property, like so...
$test.Name.Substring(0, 3)
Alternatively, if you only want the Name property (not sure where State comes from) you could use the -ExpandProperty parameter to retrieve only that one value...
$test = Get-ChildItem -Path $folderinput| select -ExpandProperty name -last 1
$test.Substring(0, 3)
As for why one snippet works and the other doesn't, that's unclear. The only difference between the two is the value of $folderoutput, which is not used; on the following line you pass $folderinput to Get-ChildItem. Are you sure $datum is set and has a Month property?

Related

How to use previous command output as a parameter in Powershell?

I need to write a Powershell one-liner to do a complex task. I need it to be strictly one line because I want to run it in a Go and Python script. The task requires taking the output of the first command and use it as a parameter in the second command.
I thought it was a simple task but I am struggling with it quite a bit. For example, the below command does not work:
$obj = Get-Item . | Get-Item $obj.Root | Format-List *
Get-Item : The input object cannot be bound to any parameters for the command either because the command does not take
pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:21
+ $obj = Get-Item . | Get-Item $obj.Root | Format-List *
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\Users\fhcat:PSObject) [Get-Item], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.GetItemCommand
What am I doing wrong?
Strictly one line sounds like a personal preference rather than a technical requirement.
However, you can end a statement with a semicolon or process the input via ForEach-Object
$obj = Get-Item .; Get-Item $obj.Root | Format-List *
or
Get-Item . | ForEach-Object {Get-Item $_.Root} | Format-List *

Powershell pipeline foreach-object variable is null

I have a super simple script that I swear I use almost every day, but for some unknown reason my $_. variable is null.
Could someone please spot check it? there is only one column in the CSV I am importing, however it has no header so i don't know if that is what is causing it.
$results = import-csv C:\####\####\####\finddestinguishednamesof.csv | foreach-object {
Get-ADGroup $_. -Properties SamAccountName,DistinguishedName
}
$results | select SamAccountName,DistinguishedName |
Export-Csv C:\Users\laruemi\Desktop\test.csv -NoTypeInformation
I keep getting this error and do not know why.
Get-ADGroup : Cannot validate argument on parameter 'Identity'. The Identity property on the argument is null or empty.
At C:\Users\laruemi\Desktop\getdestinguishedname.ps1:2 char:13
+ Get-ADGroup $_. -Properties SamAccountName,DistinguishedName
+ ~~
+ CategoryInfo : InvalidData: (:) [Get-ADGroup], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
The list of CSV's I am importing is just a list of SAMAccountNames with no header. i dont think that should cause this error, but it might. Can someone please give me a sanity check?

Checking to see if PowerShell Command worked, Crap Error

Needed to clean up a winmail.dat issue by adding a contact and setting a couple of parameters. All worked as shown, except the command to test that it worked.
Get-MailContact | Select randomemail#email.com | Select -UseMapiRichTextFormat
What is the reason for this failure?
Select-Object : A parameter cannot be found that matches parameter
name 'UseMapiRichTextFormat'. At line:1 char:62 + ... t 1 Select
support#solidpe.maxdesk.us 1 Select -UseMapiRichTextFormat +
---------------------- + CategoryInfo : InvalidArgument: (:) [Select-Object], ParameterBindingException + FullyQualifiedErrorId :
NamedParameterNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand
I think what you actually need is this:
Get-MailContact |
Where-Object {$_.ExternalEmailAddress -eq 'randomemail#email.com'} |
Select-Object -Property UseMapiRichTextFormat
Where-Object limits the result set by comparing each contact's ExternalEmailAddress property and only including the objects that match in the output (which should only be one)
Select-Object limits the output object members to a subset of the original members

I can't get Powershell StartsWith function to work

I'm trying to create a Powershell script that prints out only certain AD groups from the Folder Permission settings. However for some reason Powershell doesn't recognize StartsWith function.
("C:\folder" | get-acl).Access | ForEach-Object { if (($_.IdentityReference).StartsWith("sl_test")) { continue }; $_ }
When I run this I got errors similar to this for every foreach object:
Method invocation failed because [System.Security.Principal.NTAccount] does not contain a method named 'StartsWith'.
At C:\temp\test.ps1:1 char:56
+ ("C:\folder" | get-acl).Access | ForEach-Object { if (($_.IdentityReference).St ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Any suggestions on how to get this to work?
IdentityReference is a [System.Security.Principal.NTAccount]according to your error message.
But .StartWith is a method on the String type. If you call a method, Powershell does no magic for you, AFAIK.
Try ... ($_.IdentityReference) -match "^sl_test" ..., which should do the implicit string conversion.
If you want the string representation of an IdentityReference (regardless of whether it's and NTAccount object or a SID), you can reference the Value property:
$_.IdentityReference.Value.StartsWith('sl_test')
Try:
Get-Acl -Path "C:\folder" | Select-Object -ExpandProperty Access | Where-Object {$_.IdentityReference -like "sl_test*" }
You can customize the output with an additional | Select-Object -Property XY

When piping array of integers the $_ variable is null?

Take this as an example:
$var = "one","two","three"
0..2 | select-object $var[$_]
Index operation failed; the array index evaluated to null.
At line:1 char:27
+ 0..2 | select-object $var[ <<<< $_]
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArrayIndex
Why is $_ a null?
I can't figure why you are using select-object
try this:
$var = "one","two","three"
0..2 | % { $var[$_]}
You can also use select-object in a different way:
$var | select -Index (0..2)
And btw, if all you want to do is extract element in the array, you can do array slicing:
$var[0..2]
If you want to use select-object you need to create a hashtable, aka calculated property, and give it a name and expression keys. The result would be objects with one property, var, in the following example
0..2 | select #{name='var';expression={$var[$_]}}
var
---
one
two
three