Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Powerhsell 5 versions and builds

$
0
0

Hi Team,

I know this is simple, but i was unable to find, the powershell release versions build numbers documents. Could anyone help with url link


Naveen Kumar


Script to rename Windows

$
0
0

Hi,

Is it possible to rename Windows 8.1 computer without unjoin domain with a powershell script?

Thanks,

Export Usergroup Membership Powershell

$
0
0

This is what im looking forward to get but it has been hard for me since im litteraly new in Powershell

GroupAccountname
group1            user1 
group1            user2 
group1            user3 
group2            user4 
group2            user5 
group3            user6 
group3            user7 
group3            user8 
group4            user9 
group5            user10 

Do we have a windows powershell script to Display User Profile

$
0
0

Can this be scripted in Powershell to display all the user attributes?

PowerShell combining objects

$
0
0

In the following script I am attempting to pull some basic data from Exchange and combine the objects into a single output. I believe the problem is tied to the output assigned to my $Usage variable, as there are going to be multiple results for each database. I'd also like to sort the data by the "Time In Server" column.

The output I get currently looks like this:

Database     | Display Name | Time In Server

DB01

DB02

DB03

The output I'd like to achieve:

Database     | Display Name | Time In Server

DB01             User 3              250

DB01             User 4              225 

DB03             User 2              190

DB03             User 1              100

# Create a new variable with today's date.
$todaysDate = (Get-Date).tostring("MM-dd-yyyy")

# Retreive a list of mailbox databases
$Databases = (Get-MailboxDatabase | where {$_.Name -like "DB*"} | select Name)

# Create an array to store the output
$Output = @()

# Go through each database and retreive the usage statistics
foreach ($Database in $Databases) {
		
		$Usage = (Get-StoreUsageStatistics -Database $Database.Name | where {$_.TimeInServer -gt "5000"} | Select DisplayName, TimeInServer)

	# Create a new object to store this information
	$OutputItem = New-Object PSObject;

	$OutputItem | Add-Member NoteProperty "Database Name" $Database.Name;
	$OutputItem | Add-Member NoteProperty "Display Name" $Usage.DisplayName;
	$OutputItem | Add-Member NoteProperty "Time In Server" $Usage.TimeInServer;

	# Add the object to our array of output objects
	$Output += $OutputItem;

	}

$Output | Export-CSV "$todaysDate.csv" -NoTypeInformation


Cluster Report Script Error

$
0
0

Hi Guys

I`ve been looking for a powershell script to check windows failover cluster health checks/status and I`ve found one from gallery link but it`s

param($cluster_name, $path, $web_path); 
# Function to send emails 
# Usage: 
# sendEmail "172.16.200.25" 25 "NorthClusterReportTest" "Body message" $null "nveeam@psg.co.za" "raymond.mkhize@psg.co.za" "dale.mdlalose@psg.co.za"; 
function sendEmail 
{ 
    param ($smtpServer, $smtpPort, $subject, $body, $attachment, $To, $From); 
    # configure server 
    $smtp = New-Object System.Net.Mail.SmtpClient; 
    $smtp.Host = $smtpServer; 
    $smtp.Port = $smtpPort; 
    # create the email 
    $email = New-Object System.Net.Mail.MailMessage; 
    $email.From = $From; 
    $email.Subject = $subject; 
    $email.Body = $body; 
    # Split emails into an array and add each recipient 
    $toEmails = $To.Split(","); 
    foreach($recipient in $toEmails) 
    { 
        $email.To.Add($recipient); 
    } 
    # if attachment filepath has been provided 
    if($attachment -ne $null) 
    { 
        $att = New-Object Net.Mail.Attachment($attachment); 
        $email.Attachments.Add($att); 
    } 
    $email.IsBodyHtml = $true; 
    # send the email 
    $smtp.Send($email); 
} 
Import-Module FailoverClusters; 
# Write & manages the cluster state text files 
function Write-ClusterState 
{ 
    param ($object, $name); 
    if(Test-Path -Path "$path$name.txt") 
    { 
        Move-Item -Path "$path$name.txt" $($path + "previous`_$name.txt") -Force; 
    } 
    $content = $object | ConvertTo-Html -Fragment; 
    $content | Set-Content -Path "$path$name.txt"; 
} 
# Runs various cmdlets against the cluster to get state info 
function Get-ClusterInfo 
{ 
    param ($cluster); 
    # Get information about one or more nodes (servers) in a failover cluster. - http://technet.microsoft.com/en-us/library/ee460990.aspx 
    $cluster_nodes = Get-ClusterNode -Cluster $cluster | Select-Object -Property Name, State; 
    # Get information about one or more clustered services or applications (resource groups) in a failover cluster. - http://technet.microsoft.com/en-us/library/ee461017.aspx 
    $cluster_group = Get-ClusterGroup -Cluster $cluster | Select-Object -Property Name, OwnerNode, State, DefaultOwner, AutoFailbackType; 
    # Get information about one or more resources in a failover cluster. - http://technet.microsoft.com/en-us/library/ee461004.aspx 
    $cluster_resources = Get-ClusterResource -Cluster $cluster | Select-Object -Property Name, OwnerNode, OwnerGroup, State; 
    # Uses a few cmdlets to get details of possible owners for cluster resources - http://technet.microsoft.com/en-us/library/ee460989.aspx 
    # Expand Property used here to flatten array type data 
    $cluster_owner_node = Get-ClusterResource -Cluster $cluster | Get-ClusterOwnerNode | Select-Object -Property ClusterObject -ExpandProperty OwnerNodes | Select-Object -Property ClusterObject, Name;; 
    # Get information about one or more networks in a failover cluster. - http://technet.microsoft.com/en-us/library/ee461011.aspx 
    $cluster_network = Get-ClusterNetwork -Cluster $cluster | Select-Object -Property Name, Role, Address, State; 
    # Get information about one or more network adapters in a failover cluster. - http://technet.microsoft.com/en-us/library/ee460982.aspx 
    $cluster_network_interface = Get-ClusterNetworkInterface -Cluster $cluster | Select-Object -Property Name, Network, Node, State; 
    # Get information about permissions that control access to a failover cluster. - http://technet.microsoft.com/en-us/library/ee460977.aspx 
    $cluster_access = Get-ClusterAccess -Cluster $cluster | Select-Object -Property IdentityReference, AccessControlType, ClusterRights; 
    # write report files 
    Write-ClusterState $cluster_nodes "cluster_nodes"; 
    Write-ClusterState $cluster_group "cluster_group"; 
    Write-ClusterState $cluster_resources "cluster_resources"; 
    Write-ClusterState $cluster_owner_node "cluster_owner_node"; 
    Write-ClusterState $cluster_network "cluster_network"; 
    Write-ClusterState $cluster_network_interface "cluster_network_interface"; 
    Write-ClusterState $cluster_access "cluster_access"; 
} 
# This function adds additional information to  
# the cluster headers so we know a little more about 
# what it's showing us 
function AddLinkFor-Header 
{ 
    param ($header); 
    switch ($header) 
    { "Cluster Nodes" {"Get information about one or more nodes (servers) in a failover cluster. - <a href='http://technet.microsoft.com/en-us/library/ee460990.aspx'>info</a>"} "Cluster Group" {"Get information about one or more clustered services or applications (resource groups) in a failover cluster. - <a href='http://technet.microsoft.com/en-us/library/ee461017.aspx'>info</a>"} "Cluster Resources" {"Get information about one or more resources in a failover cluster. - <a href='http://technet.microsoft.com/en-us/library/ee461004.aspx'>info</a>"} "Cluster Owner Node" {"Uses a few cmdlets to get details of possible owners for cluster resources - <a href='http://technet.microsoft.com/en-us/library/ee460989.aspx'>info</a>"} "Cluster Network" {"Get information about one or more networks in a failover cluster. - <a href='http://technet.microsoft.com/en-us/library/ee461011.aspx'>info</a>"} "Cluster Network Interface" {"Get information about one or more network adapters in a failover cluster. - <a href='http://technet.microsoft.com/en-us/library/ee460982.aspx'>info</a>"} "Cluster Access" {"Get information about permissions that control access to a failover cluster. - <a href='http://technet.microsoft.com/en-us/library/ee460977.aspx'>info</a>"} 
        default {"No additional info available."} 
    } 
} 
function Build-ClusterReport  
{ 
    param ($location, $cluster_name); 
    $state_changed = $false; 
    $css = Get-Content -Path $($path + "resources\style.css"); 
    $generated = Get-Date; 
    $html_report = "<html><head>$css</head><body><h1>Cluster Report for $cluster_name $generated</h1>"; 
    # each cluster report file 
    $files = Get-ChildItem "$location\cluster_*.txt"; 
    foreach($file in $files) 
    { 
        # If the previous_cluster_*.txt files exists  
        # we compare the contents of each so we can 
        # tell if the state of the cluster has changed 
        $file_name = $file.Name; 
        $header = Do-Captialize $file_name.Replace("_", " ").Replace(".txt", ""); 
        if(Test-Path -Path "$location\previous`_$file_name") 
        { 
            [string]$current = Get-Content -Path $file; 
            [string]$previous = Get-Content -Path "$location\previous`_$file_name"; 
            $compare = Compare-Object $current $previous; 
            $info = AddLinkFor-Header $header; 
            if($compare.Length -gt 0) 
            { 
                $state_changed = $true; 
                $html_report += "<p><h1>$header</h1>  - $info</p>" + "<h3>Change in cluster state!</h3>" + "<table><tr><td><h2>Current state</h2>" + $current + "</td><td>" + "<h2>Previous state</h2>" + $previous + "</td></tr></table>"; 
            } 
            else 
            { 
                $html_report += "<p><h1>$header</h1> - $info</p>" + $current; 
            } 
        } 
    } 
    $html_report += "</body></html>"; 
    return $html_report; 
} 
# Upcase Code from http://www.thejohnsonblog.com/2010/11/25/capitalizing-first-letter-of-every-word-with-powershell-2/ 
function Do-Captialize 
{ 
    param ($name); 
    $name = [Regex]::Replace($name, '\b(\w)', { param($m) $m.Value.ToUpper() }); 
    return $name; 
} 
Get-ClusterInfo $cluster_name; 
$datetime = Get-Date -Format "yyyy_MM_dd_hh_mm_ss"; 
# archive old report RC Too many files written! 
#Rename-Item $($path + "$cluster_name.html") "$datetime`_$cluster_name.html"; 
#Move-Item $($path + "$datetime`_$cluster_name.html") $($path + "archive"); 
$rpt = Build-ClusterReport $path $cluster_name; 
$rpt | Set-Content -Path $($path + "$cluster_name.html"); 
# Move the report onto a web server 
Copy-Item "$path\$cluster_name.html" "$web_path" -Force; 
if($rpt.Contains("Change in cluster state")) 
{ 
    # send an email alert 
    $subject = "$cluster_name - This is North Cluster Report Test Email"; 
    $report = $rpt; 
    sendEmail "172.16.200.25" 8025 $subject $report $transcript "nveeam@psg.co.za" "raymond.mkhize@psg.co.za"; 
}

giving me an error when trying to run it. The error is as follows, and I`ve edited the script accordingly as per instructions provided on the same link:

Get-ClusterNode : Cannot validate argument on parameter 'Cluster'. The argument is null or empty. Provide an 
argument that is not null or empty, and then try the command again.
At C:\IT\Cluster Reports\ClusterReport.ps1:55 char:47
+     $cluster_nodes = Get-ClusterNode -Cluster $cluster | Select-Objec ...
+                                               ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ClusterNode], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.FailoverClusters.PowerShell.GetNodeCommand
 
Get-ClusterGroup : Cannot validate argument on parameter 'Cluster'. The argument is null or empty. Provide an 
argument that is not null or empty, and then try the command again.
At C:\IT\Cluster Reports\ClusterReport.ps1:57 char:48
+     $cluster_group = Get-ClusterGroup -Cluster $cluster | Select-Obje ...
+                                                ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ClusterGroup], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.FailoverClusters.PowerShell.GetClusterGroup 
   Command
 
Get-ClusterResource : Cannot validate argument on parameter 'Cluster'. The argument is null or empty. Provide an 
argument that is not null or empty, and then try the command again.
At C:\IT\Cluster Reports\ClusterReport.ps1:59 char:55
+ ...    $cluster_resources = Get-ClusterResource -Cluster $cluster | Selec ...
+                                                          ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ClusterResource], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.FailoverClusters.PowerShell.GetResourceComm 
   and
 
Get-ClusterResource : Cannot validate argument on parameter 'Cluster'. The argument is null or empty. Provide an 
argument that is not null or empty, and then try the command again.
At C:\IT\Cluster Reports\ClusterReport.ps1:62 char:56
+ ...   $cluster_owner_node = Get-ClusterResource -Cluster $cluster | Get-C ...
+                                                          ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ClusterResource], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.FailoverClusters.PowerShell.GetResourceComm 
   and
 
Get-ClusterNetwork : Cannot validate argument on parameter 'Cluster'. The argument is null or empty. Provide an 
argument that is not null or empty, and then try the command again.
At C:\IT\Cluster Reports\ClusterReport.ps1:64 char:52
+     $cluster_network = Get-ClusterNetwork -Cluster $cluster | Select- ...
+                                                    ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ClusterNetwork], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.FailoverClusters.PowerShell.GetNetworkComma 
   nd
 
Get-ClusterNetworkInterface : Cannot validate argument on parameter 'Cluster'. The argument is null or empty. 
Provide an argument that is not null or empty, and then try the command again.
At C:\IT\Cluster Reports\ClusterReport.ps1:66 char:71
+ ... ork_interface = Get-ClusterNetworkInterface -Cluster $cluster | Selec ...
+                                                          ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ClusterNetworkInterface], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.FailoverClusters.PowerShell.GetNetworkInter 
   faceCommand
 
Get-ClusterAccess : Cannot validate argument on parameter 'Cluster'. The argument is null or empty. Provide an 
argument that is not null or empty, and then try the command again.
At C:\IT\Cluster Reports\ClusterReport.ps1:68 char:50
+     $cluster_access = Get-ClusterAccess -Cluster $cluster | Select-Ob ...
+                                                  ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ClusterAccess], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.FailoverClusters.PowerShell.GetClusterAcces 
   sCommand
 
Copy-Item : Cannot find path 'C:\.html' because it does not exist.
At C:\IT\Cluster Reports\ClusterReport.ps1:152 char:1
+ Copy-Item "$path\$cluster_name.html" "$web_path" -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\.html:String) [Copy-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
 

Using the match feature throughan array

$
0
0

I've been trying to write a script and in a section of it, I need to compare names of users to a explicit list. So Powershell is presented with the names of all users on a specific system and I need to find any users that start with a certain string. All accounts that need to be counted start with "xxx" or "yyy" but have varying length.

Now this bit is fine and I could use something like the below line to count these.

Where-Object {$_.name -Match "xxx"} | Select Name | Measure

But I don't want to have multiple lines doing the same thing so comparing them to items in an array would be great. For this, I have the below lines.

$valuesToMatch = @("xxx""yyy"
    )

Where-Object {$valuesToMatch -Match $_.name}

But when I am using the method above (I have, of course, missed out various lines for sake of simplicity) it only counts it if it is an exact match. A.K.A. if the list of users was xxx, xxxbob this would only match with xxx and not xxxbob.

With the first line it matched to include but when checking from the array it has to be exact, what is the cause / workaround of this?

Appened to adjacent cell in CSV file

$
0
0

HI,

I'm not great with powershell but it's what I know best so I'm trying to use it to do the following:

I need to extract data like below from AD:

$users = (import-csv "$path\users.csv").users
Foreach ($user in $users){

$Dname = Get-ADUser $user -properties TelephoneNumber| select TelephoneNumber
$Email =  Get-ADUser $user -properties UserPrincipalName | select UserPrincipalName
}

and append it to an adjacent cell in an existing csv file(i.e specify the column it writes to and only write on the same row as the matching username in users.csv)

any assistance with this would be appreciated

regards,

Ian


New-Item : The given path's format is not supported - SOLVED

$
0
0

I have function for getting MicrosoftSubscriptionData from Partner Center

function Export-MicrosoftSubscriptionData {

[CmdletBinding()]    param ( 

[Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string[]]$CustomerId    #TODO: Add optional parameters    )  begin { $ArrayOfSubscriptions = [System.Collections.ArrayList]@()  } process { Try { $CustomerId.ForEach({ #$CurrentCustomerId = $_                 $CurrentCustomerId = "2"                                 $Subscriptions = Get-PartnerCustomerSubscription - CustomerId $CurrentCustomerId                                                                  $Subscriptions.ForEach({                                   $Subscription = [Order]::new()

$Subscription.PopulateMicrosoftPartnerData($_.SubscriptionId, $CurrentCustomerId)                                               $ArrayOfSubscriptions.Add($Subscription) }) }) } Catch { Write-Host "Caught an exception:" -ForegroundColor Red      Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red    Write-Host "Exception Message: $($_.Exception.Message)" - ForegroundColor Red            

errorLog $LogPath "Exporting" "subscription for Customer:$ArrayOfSubscriptions failed"                      } } end { }

In case some of customerID fails i want to write it in some log file, so i created following function

$LogPath = Get-Location

function errorLog {
  
  param([string]$LogPath, [string]$Msg, [string]$exportType)
  if((Test-Path "$LogPath\$exportType.log") -eq $false) {New-Item "$LogPath\$exportType.log" -ItemType File}
  Write-Host "$(Get-Date): $Msg $exportType" -ForegroundColor Green
  Add-Content "$LogPath\$exportType.log" -Value "$(Get-Date): $Msg $exportType failed"
}


Then i called it in Catch block

I tried to simulate error, provided dummy CustomerID

 Catch {
            Write-Host "Caught an exception:" -ForegroundColor Red
            Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
            Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red 
            errorLog $LogPath "Exporting" "subscription failed"                  
        }     


This works without error, and it writes in log file that export failed for every Customer

11/15/2019 10:27:55: Exporting subscription failed

So i added CurrentCustomerID variable to errorLog function

 

 Catch {
            Write-Host "Caught an exception:" -ForegroundColor Red
            Write-Host "Exception Type: $($_.Exception.GetType().FullName)" -ForegroundColor Red
            Write-Host "Exception Message: $($_.Exception.Message)" -ForegroundColor Red 
            errorLog $LogPath "Exporting" "subscription for Customer:$CurrentCustomerId failed"                  
}     


Now i'm getting 

New-Item : The given path's format is not supported.
At line:11 char:58+ ... og") -eq $false) {New-Item "$LogPath\$exportType.log" -ItemType File}+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [New-Item], NotSupportedException+ FullyQualifiedErrorId : System.NotSupportedException,Microsoft.PowerShell.Commands.NewItemCommand


So error happens only when i specify CustomerID in error function, is there any way to fix this ?



How does Powershell Get multiple specified user properties using the get-aduser filter

$
0
0

How does Powershell Get multiple specified user properties using the get-aduser filter

I need to get the email addresses of users a, b, c ,It needs to be obtained once in -fiter。

Get-ADUser -Filter 'SamAccountName -like “a” -and Mail -like “ *”'

Or some other method.

Second question

$DN = "ou=chx,DC=hpi,DC=com,DC=cn"
$1 = "aa","bb"
########################################
Get-ADUser -SearchBase $DN -Filter "SamAccountName -like '$1[0]'"

The user cannot be obtained using this method and how to implement it.

Remove i:0#.w|ad\ Prefix using PowerShell and TrimStart

$
0
0

I am trying to remove 

i:0#.w|ad\

From accounts listed in the groups in SharePoint 2013. Some of our accounts start with ad, which I obviously want to preserve. However I cannot work out how to only trim the first 'ad'. I cannot prevent a second 'ad' from being trimmed, so "i:0#.w|ad\adxxxx" always gives "xxxx".

$testString = "i:0#.w|ad\adxxxx";
$testString.TrimStart($myTrim);

Here is a list of what I have tried (yes, many of these are not even close and just symptomatic of my increasing desperation). The 'i:0#.w|' seems to trim just fine on it's own without any escaping, but of course leaves '\ad' which I want to remove.

$myTrim = 'i:0#.w\|"ad\"?'
$myTrim = 'i:0#.w|"ad\"?'
$myTrim = 'i:0#.w|"ad\"{1}'
$myTrim = "(i:0#.w\|ad\)"
$myTrim = "(i:0#.w|ad\)"
$myTrim = "(i:0#\.w\|ad\)"
$myTrim = "(i:0#\.w\|ad\\)"
$myTrim = "[i:0#.w\|ad\\]"
$myTrim = "[i:0#.w|ad\]"
$myTrim = "<i:0#\.w\|*?\\ad>"
$myTrim = "<i:0#\.w\|>?<\\ad>"
$myTrim = "<i:0#\.w\|>*?<\\ad>"
$myTrim = "<i:0#\.w\|><\?\ad>"
$myTrim = "<i:0#\.w\|><\\ad>"
$myTrim = "<i:0#\.w\|><\\ad>(0)"
$myTrim = "<i:0#\.w\|><\\ad>(1)"
$myTrim = "<i:0#\.w\|><\\ad>{1}"
$myTrim = "<i:0#\.w\|ad\\>"
$myTrim = "i:0#.w\|","ad\?"
$myTrim = "i:0#.w\|ad\?"
$myTrim = "i:0#.w|?ad\"
$myTrim = "i:0#.w|""ad?\"
$myTrim = "i:0#.w|(ad\)?"
$myTrim = "i:0#.w|(ad\){1}"
$myTrim = "i:0#.w|a?d?\?"
$myTrim = "i:0#.w|ad?\"
$myTrim = "i:0#.w|ad"
$myTrim = "i:0#.w|ad\?"
$myTrim = "i:0#.w|ad\"
$myTrim = "i:0#\.w\|*?\\ad"
$myTrim = "i:0#\.w\|ad\?"
$myTrim = "i\:\0\#\.w\|ad\?"
$myTrim = "i\:0\#\.w\|*?\\ad"
$myTrim = "i\:0\#\.w\|ad\?"

Powershell Looping issue

$
0
0

Hi , I am learning PowerShell and newbie to PowerShell.

Can I get some help on below.

I created three files :

  1. Testfile
  2. BB-Thisisfile1223 ****?????
  3. CC-ThisisthelongestfileThisisthelongestfileThisisthelongestfileThisisthelongestfileThisisthelongestfileThisisthelongestfile

4. CC-ThisisthelongestfileThisisthelongestf &&& *** ileThisisthelongestfileThisisthelongestfileThisisthelongestfileThisisthelongestfile

5. Testfile 123 **** ??? ::

I am using below code , to get the output:

Ask from me:

I am getting output as expected for first 2 files as below

Output1 : File is not in defined format

Output2 : File has wild card operators

But even for 3rd file , I am getting below output , please help by correcting it.

Output3 : File has wild card operators

Also: I would like to get outputs exactly matching below:

File has wild card characters & more than 50 characters

File has Invalid format & has wild card operators

$q = "select * from table1"

$exec_q = Invoke-Sqlcmd -serverinstance abc -database new -Query $q $min = $exec_q | select name -ExpandProperty name foreach($n in $min){ if( $n -notmatch 'AA-'` -and $n -notmatch 'BB-'` -and $n -notmatch 'CC-'` ){ Write-Host "File is not in defined format" } Elseif( $n -match 'AA-'` -or $n -match 'BB-'` -or $n -match 'CC-'` -or $n -match @('[,/\:*?"<>&;]') ){ Write-Host "File has wild card operators" } Elseif( $n -match 'AA-'` -or $n -match 'BB-'` -or $n -match 'CC-'` -or $n.length -gt 70 ){ Write-Host "File has more than 50 characters" } Elseif( $n -match 'AA-'` -or $n -match 'BB-'` -or $n -match 'CC-'` -or $n.length -gt 70 ` -or $n -match @('[,/\:*?"<>&;]')){ Write-Host "File has wild card characters & more than 50 characters" } Elseif( $n -notmatch 'AA-'` -and $n -notmatch 'BB-'` -and $n -notmatch 'CC-'` -and $n.length -gt 70 ` -and $n -notmatch @('[,/\:*?"<>&;]')){ Write-Host "File has Invalid format & has wild card operators" }}



Best Regards,SQLBoy





Task Scheduler PowerShell Script

$
0
0

I have a script that finds a specific process, if it is running, terminate, wait x seconds, run the program again. When I test in PowerShell, it works as designed. However, I add the script to Task Scheduler it does not work. 

Script Example:

(Get-WmiObject -Class Win32_Process -Filter "Name = 'notepad.exe'").Terminate();
Start-Sleep 10
Start-Process -FilePath "C:\Windows\notepad.exe"

Not sure if that is the correct path to start-process but it's just an example. 

Task Scheduler Setup (Export XML):

<?xml version="1.0" encoding="UTF-16"?><Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Date>2019-10-15T16:02:32.6662873</Date><Author>Domain\Username</Author><URI>\RestartNotepadDaily</URI></RegistrationInfo><Triggers><CalendarTrigger><StartBoundary>2019-10-15T04:00:00</StartBoundary><Enabled>true</Enabled><ScheduleByWeek><DaysOfWeek><Monday /><Tuesday /><Wednesday /><Thursday /><Friday /></DaysOfWeek><WeeksInterval>1</WeeksInterval></ScheduleByWeek></CalendarTrigger></Triggers><Principals><Principal id="Author"><UserId>SID GUID HERE</UserId><LogonType>Password</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>true</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>false</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable><IdleSettings><StopOnIdleEnd>true</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden><RunOnlyIfIdle>false</RunOnlyIfIdle><DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession><UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine><WakeToRun>false</WakeToRun><ExecutionTimeLimit>PT2H</ExecutionTimeLimit><Priority>7</Priority><RestartOnFailure><Interval>PT1M</Interval><Count>20</Count></RestartOnFailure></Settings><Actions Context="Author"><Exec><Command>PowerShell.exe</Command><Arguments>-NoProfile -ExecutionPolicy Bypass -File "c:\scripts\NotePadRestartDaily.ps1"</Arguments></Exec></Actions></Task>

Can anyone provide me with some suggestions on why I cannot get this to work? I have been bashing my brain for the past month trying different things to no success.

Server Version: Windows Server 2015 Datacenter v1607 (Azure VM)

Multiple creds with Start-Process

$
0
0

Hello,

is it possible to initate DSA.msc with multiple credentials when working from a non Domain Admin account? One set of creds to run the process and another to open DSA.msc. 

Here is what I have so far:

Start-Process powershell -Credential $cred  -ArgumentList '-command &{DSA.msc /DOMAIN="domain.local"','/SERVER="somedc"}'

It does open the snapin as Domain Admin for that DC but only after UAC prompts me for the Same Credentials that I have in the Credential parameter. Its as if its ignoring the credentials I have in the cred file. Please note that I have powershell running as a Domain Admin but for my domain not the DC I am attempting to connect to. 

If I run this command for my current domain that I am logged in, it opens the snapin with no other prompts, it just works:

Start-Process powershell -Credential $Currentcred  -ArgumentList '-command &{DSA.msc /DOMAIN="mydomain.local"','/SERVER="mydc"}'

Compare Objects and keep additional columns

$
0
0

I'm trying to figure out the best way to accomplish this task. Any guidance is much appreciated!

I have 2 CSV files. The 1st file has 2 columns (Computer & Email). The 2nd file has 1 column (Email). I need to compare both files based on the Email column and return the matches. The output should included the Email and Computer columns.

MasterFile.csv

ComputerEmail
Computer1userA@company.com
Computer2userB@company.com
Computer3userC@company.com
Computer4userA@company.com

CompareFile.csv

Email
userA@company.com
userC@company.com

My code thus far:

$MasterCSV = Import-Csv -Path C:\MasterFile.csv
$CompareCSV = Import-Csv -Path C:\CompareFile.csv
Compare-Object -ReferenceObject $MasterCSV.Email -DifferenceObject $CompareCSV.Email -IncludeEqual -ExcludeDifferent | Select *


Import schedule task in windows server 2016

$
0
0

I have around 200 .xml task which I copied from old windows 2008 server that I need to import with same name and it also use service account and password.  I tried below script and its not working in 2016. do yo have any working script for windows 2016?

$task_path = "D:\Schedule task\*.xml"
$task_user = "domain\serviceaccount"
$task_pass = "password"

$sch = New-Object -ComObject("Schedule.Service")
$sch.connect("localhost")
$folder = $sch.GetFolder("\")

Get-Item $task_path | %{
 $task_name = $_.Name.Replace('.xml', '')
 $task_xml = Get-Content $_.FullName

 $task = $sch.NewTask($null)
 
 $task.XmlText = $task_xml

 $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
 
}


Get list of former employees using outlook who left organisation

$
0
0

I have to get list of former employees from outlook, is there any api where I will search fname.lname@domain.com, will get the user exists or not in company or status as presence unknown or employee left or something meaningful

Further I have to use the list to delete names form json/yml files, below cmdlet gives me an error that cmdlet is unable to recognize 

Get-Mailbox -ResultSize unlimited | Get-MailboxPermission -User fname.lname@domain.com |  Ft -a

While Trying to send Powershell Data to php form getting the Error: You cannot call a method on a null-valued expression

$
0
0

Hi,

I am trying to send the data of powershell to the registration form in php it is showing an error

Code:

Add-Type -AssemblyName Microsoft.VisualBasic

 $orderID= hostname
 $orderID1= (get-wmiobject -Class win32_bios).SerialNumber
 $OrderIDTextBox="hname" #  id of the Field Hostname in Registration form

$OrderIDTextBox1="sno"# id of the field Serial no in Registration form
$iterator = 1;
$IE = New-Object -ComObject InternetExplorer.Application
$ie.visible = $true
$ie.navigate("http://localhost/asset.php")
While ($IE.Busy -eq $true) {Start-Sleep -Milliseconds 2000} 

    Start-Sleep -Seconds 3
$ie.Document.getElementById("$orderIDTextBox").value= "$OrderID"
$ie.Document.getElementById("$orderIDTextBox1").value= "$OrderID1"

error:

 

You cannot call a method on a null-valued expression.
At C:\Users\tpladmin\desktop\as.ps1:16 char:1
+ $ie.Document.getElementById("$orderIDTextBox").value= "$OrderID"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\Users\tpladmin\desktop\as.ps1:17 char:1
+ $ie.Document.getElementById("$orderIDTextBox1").value= "$OrderID1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Created the Value for the $ie with a Com Object. Web page with the url : http://localhost/asset.php is opening but unable to send the data to forms. Please help.

Thanks in Advance.

 

Form Textbox text | Get-Content

$
0
0

Need some support with PS1 form, i have develop form with textbox and dialog for text file selection, now i'm trying to pass textbox content to get-content command to get all info in text file, Example (Get-Content Textbox.Text) but nothing happens and when use write-host comment to see it is fine show correct text from textbox (C:\Temp\Text.txt) but not  pass parameter in Get-Content command?

Your support appreciated.

Thanks


Support@Mytechnet.me

using color with Read-Host

$
0
0

Is there a way to use -foregroundcolor with Read-Host?

In the below example, I would like to change the color of "[quit]", but leave all other text at the default color:

$input = Read-Host "Select an option or type [quit] to exit"

Viewing all 21975 articles
Browse latest View live