powershell string contain only number - powershell

I have an array with folder names. I want to loop thru this array and find out if an entry is only 7 in length and only contain numbers.
Can anyone please push me in the correct direction? Thanks!

One solution is while looping through the array names check if the two conditions are met like so:
foreach ($name in "test", "1234567", "test02", "001") {
if ($name.Length -eq 7 -and $name -match '^\d+$'){
Write-Host $name
}
}

As far as i understood your question :
function Is-Numeric ($Value)
{
return $Value -match "^[\d\.]+$"
}
$birds = "owl","crow","robin","wren","jay","123"
foreach ($bird in $birds) { if($bird.length -eq 3 -and (Is-Numeric $bird)) {"$bird"} }
just switch it to your case :)

Related

PowerShell Isn't Parsing Data as Expected // Basic PowerShell Operator Question

I have a pretty nooby question regarding the proper usage of certain operators.
I am writing a script that pulls data out of a CSV. The script asks the user to enter a location # and then is supposed to output the IP of their server.
The script works as expected except on rows where the location number also has other text in it like numbers or special characters.
Here is an example CSV to illustrate my problem:
Loc#,State,Server IP
1,NY,10.0.0.1
2,CA,10.0.0.2
3,WA,10.0.0.3
4 (inp),KY,10.0.0.4
My script looks something like this:
$CSV = import-csv C:\users\Self\MyProject.csv
$location = read-host "enter the location #"
foreach( $row in $CSV){
if($row.loc# -eq $location)
{
write-host $row.'Server IP'
}
Now, this script works as expected unless the user chooses location 4. If the users chooses location 4, then the $location variable is left blank.
Ok, this makes a little bit of sense since I'm using the -eq operator. But even if I use the -contains operator I get the same results.
Here is another way of showing my problem:
$number = "10 ten"
if ($number -contains "10"){ (Write-Host "true")} else{ write-host "false"}
false
Now, why isn't the output showing as "true" since that $number variable does indeed contain "10"?
Any help is much appreciated,
Thanks
As it seems, Location can have a random value and not only digits, normally you could use -match as Mahmoud Moawad pointed out in his comment, however this could also bring you problems since there is no specific pattern you can follow there is also no clear way of how you can filter the specific value. What I would personally do is give the user a list where he can choose the Location by Index:
$csv = Import-Csv C:\users\Self\MyProject.csv
$csv.foreach({
begin
{
'- Choose a location:'
$i = 0
$map = #{}
}
process
{
$map[(++$i)] = $_
"[$i] - {0}" -f $_.'Loc#'
}
})
$question = { Read-Host 'Index' }
while($true)
{
$index = (& $question) -as [int]
if($index -ge 1 -and $index -le $csv.Count)
{
break
}
'Input must be between 1 and {0}!!' -f $csv.Count
}
$map[$index].'Server IP'
As for why -contains is not showing you $true on your condition, the Containment Operators will look for an exact match of an element:
'10 ten' -contains '10' # => False
'10 ten' -contains '10 ten' # => True
'9 nine', '10 ten' -contains '10 ten' # => True

PowerShell: Multiple Conditions within IF Statement

Im struggling to understand why the following IF statement doesn't work...
I have a PS array:
$lunchArray = #('Pizza', 'Sushi', 'Sandwich')
However the following Foreach/IF statement doesn't work as expected.
foreach ($lunch in $lunchArray) {
if ($lunch -eq 'Pizza' -and $lunch -eq 'Sushi') {
"YAY" # not working...
}
}
What am I doing wrong here?
TIA
$lunchArray = #('Pizza', 'Sushi', 'Sandwich')
foreach ($lunch in $lunchArray) {
if ('Pizza' -eq $lunch -or 'Sushi' -eq $lunch) {
"YAY" # not working...
}
}

How can I use wildcards with IF -contains on an array?

I'm working on a script backing up the schema for a database to a version control system. I just realized that replicated objects are being scripted out as well; these objects start with sp_MSupd_, sp_MSdel_, sp_MSins_, and syncobj_0x. I would like to skip these items.
I know I can do something like this:
$ExcludeObjectNames = #("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
If ($ExcludeObjectNames -contains "sp_MSdel_SampleObject")
{
Write-Host "replicated item found"
}
But this only works for exact matches. I tried adding * to the elements in the array but that did not work. And I know I can use -like, but that seems to only be for single values, not arrays.
I know I can do this
$ObjectNames = "sp_MSdel_SampleObject"
If ($ObjectNames -like "sp_MSupd_*" -OR $ObjectNames -like "sp_MSdel_*" -OR $ObjectNames -like "sp_MSins_*" -OR $ObjectNames -like "syncobj_0x*")
{
Write-Host "replicated item found"
}
This is well and fine, BUT if I find more and more things to omit, this becomes more and more ugly.
Is there a way to use wildcards with -contains on an array?
$ExcludeObjectNames = #("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
Foreach ($ExcludeObjectName in $ExcludeObjectNames) {
If ("sp_MSdel_SampleObject" -match $ExcludeObjectName)
{
Write-Host "replicated item found"
}
}
Or if you only want to edit variables in the script, you can do:
$ExcludeObjectNames = #("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
$ObjectToCheck = "sp_MSdel_SampleObject" # This variable contains your original contains target
Foreach ($ExcludeObjectName in $ExcludeObjectNames) {
If ($ObjectToCheck -match $ExcludeObjectName)
{
Write-Host "replicated item found"
}
}
If you don't like looping, you can just build a regex filter from your original array:
$ExcludeObjectNames = #("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
$ObjectToCheck = "sp_MSdel_SampleObject" # This variable contains your original contains target
$excludeFilter = '(^' + ($excludeobjectnames -join "|^") + ')' # Regex filter that you never have to manually update
If ($ObjectToCheck -match $ExcludeFilter)
{
Write-Host "replicated item found"
}

Using -notcontains to find substring within string within array

I'm trying to avoid using nested ForEach Loop as part of a larger code. To do this, I'm using the -notcontains operator. Basically, I want to see if a substring exists within a string within an array. If it exists, do nothing, if it does not exist, print "Not Found".
Here is the code...
$arr = #('"value11","value21","value31"','"value12","value22","value32"','"value13","value23","value33"')
if ($arr -notcontains "*`"value24`"*")
{
Write-Host "Not Found"
}
if ($arr -notcontains "*`"value22`"*")
{
Write-Host "Not Found 2"
}
We can see that value24 is not within any strings of the array. However, value22 is within the 2nd string in the array.
Therefor the results should output the following...
Not Found
However, instead I see the following output...
Not Found
Not Found 2
Can anyone tell me why this is happening?
-contains and -notcontains don't operate against patterns.
Luckily, -match and -like and their negative counterparts, when used with an array on the left side, return an array of the items that satisfy the condition:
'apple','ape','vape' -like '*ape'
Returns:
ape
vape
In an if statement, this still works (a 0 count result will be interpreted as $false):
$arr = #('"value11","value21","value31"','"value12","value22","value32"','"value13","value23","value33"')
if ($arr -notlike "*`"value24`"*")
{
Write-Host "Not Found"
}
My take on a solution:
($arr | foreach {$_.contains('"value24"')}) -contains $true
Using the V3 .foreach() method:
($arr.ForEach({$_.contains('"value24"')}).contains($true))
And yet another possibility:
[bool]($arr.where({$_.contains('"value24"')}))
Edit for clearer answer on what I'm looking for...
This is the only way I'm able to figure this out so far. I hope there is a much cleaner solution...
$arr = #('"value11","value21","value31"','"value12","value22","value32"','"value13","value23","value33"')
$itemNotFound = $true
ForEach ($item in $arr)
{
If ($itemNotFound)
{
If ($item -like "*`"value24`"*")
{
$itemNotFound = $false
}
}
}
if ($itemNotFound)
{
Write-Host "Not Found value24"
}
$itemNotFound = $true
ForEach ($item in $arr)
{
If ($itemNotFound)
{
If ($item -like "*`"value22`"*")
{
$itemNotFound = $false
}
}
}
if ($itemNotFound)
{
Write-Host "Not Found value22"
}
output will be:
Not Found value24

The PowerShell -and conditional operator

Either I do not understand the documentation on MSDN or the documentation is incorrect.
if($user_sam -ne "" -and $user_case -ne "")
{
Write-Host "Waaay! Both vars have values!"
}
else
{
Write-Host "One or both of the vars are empty!"
}
I hope you understand what I am attempting to output. I want to populate $user_sam and $user_case in order to access the first statement!
You can simplify it to
if ($user_sam -and $user_case) {
...
}
because empty strings coerce to $false (and so does $null, for that matter).
Another option:
if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
...
}
Try like this:
if($user_sam -ne $NULL -and $user_case -ne $NULL)
Empty variables are $null and then different from "" ([string]::empty).
The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":
$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False