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

DSC ApplyOnly

$
0
0

Hi,

I am wondering about the intended behaviour of the LCM in DSC.

In the event viewer, Application and services logs -> Microsoft -> Windows -> Desired state configuration

I can see chunks of events every 15 min where the configuration in the MOF-file is applied again and again.

Right now we are using/trying out DSC as a way to install software and applications (but perhaps other stuff in the future so we are learning right now...).

So, what we'd want is this to be a "one time effect". The MOF to be applied once and never again until Start-DscConfiguration is run again.

These are the properties of the LCM

PS C:\users\xxxxxxx> Get-DscLocalConfigurationManager


ActionAfterReboot              : ContinueConfiguration
AgentId                        : 2E7BF1A9-5A21-11EA-A51A-0050568908B3
AllowModuleOverWrite           : False
CertificateID                  :
ConfigurationDownloadManagers  : {}
ConfigurationID                :
ConfigurationMode              : ApplyOnly
ConfigurationModeFrequencyMins : 15
Credential                     :
DebugMode                      : {NONE}
DownloadManagerCustomData      :
DownloadManagerName            :
LCMCompatibleVersions          : {1.0, 2.0}
LCMState                       : Idle
LCMStateDetail                 :
LCMVersion                     : 2.0
StatusRetentionTimeInDays      : 10
SignatureValidationPolicy      : NONE
SignatureValidations           : {}
MaximumDownloadSizeMB          : 500
PartialConfigurations          :
RebootNodeIfNeeded             : True
RefreshFrequencyMins           : 30
RefreshMode                    : PUSH
ReportManagers                 : {}
ResourceModuleManagers         : {}
PSComputerName                 :

From Microsoft documentation RefreshMode: Push is "Configurations are initiated by calling the Start-DscConfiguration cmdlet. The configuration is applied immediately to the node. This is the default value." Great, this is what we are trying to accomplish.

What looks interfering is ConfigurationModeFrequencyMins but the documentation says "How often, in minutes, the current configuration is checked and applied. This property is ignored if the ConfigurationMode property is set to ApplyOnly. The default value is 15." Phew.. since we have "ApplyOnly" as "ConfigurationMode" then we are all set. Or are we?

Why does the LCM try to re-apply the MOF every 15 minutes with these LCM-settings? Is this intented behaviour?

/Daniel


Powershell Get-ADUser from one domain to a trusted domain failed

$
0
0

I have a normal domain user account called john1 in domain A.

Recently, our company merged with another company (domain B) and we set up a interforest trust between the 2x forest using selective authentication instead of forest-wide authentication.
At the same time, I was issued a domain user account john2 in domain B.

On a domain-joined machine in domain A, I logged on as john1 (my domain A account) and was able to run Get-ADUser against domain A users successfully.
On a domain-joined machine in domain B, I logged on as john2 (my domain B account) and was able to run Get-ADUser against domain B users successfully.

However, on a domain-joined machine in domain A, I opened up Powershell ISE (not Run as) and tried to run Get-ADUser command against domain B users but failed. Here is what I tried:

get-aduser -Server domainB-DC.company.com -Identity alex.hall -Credential"domainB\john2"

get-aduser :Unable to contact the server.This may be because this server does not exist, it is currently down, or it does not have the ActiveDirectoryWebServices running.At line:1 char:1+ get-aduser -Server domainB-DC.company.com -Identity alex.hall -Credent...+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:ResourceUnavailable:(alex.hall:ADUser)[Get-ADUser],ADServerDownException+FullyQualifiedErrorId:ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADUser

The same error message happened when on a domain-joined machine in domain A, I ran Run-As Powershell ISE using "domainB\john2" and issued get-aduser -Server domainB-DC.company.com -Identity alex.hall

I confirm that domainB-DC.company.com is up and running and ADWS is running as well.
On the other hand, I was able to, on domain-joined machine in doman A, run ADUC (Active Directory Users and Computers) to view domain B Active Directory by means of command-prompt with the following command: C:\WINDOWS\system32\runas.exe /u:domainB\john2 /netonly "mmc %windir%\system32\dsa.msc /domain="domainB"

I asked the firewall guy to trace if there is any traffic from my domain-joined domain A machine to domainB-DC.company.com when running the Get-ADUser cmdlet and surprisingly he said he saw no traffic.

Does anyone encounter such problems?

Start process in background

$
0
0

When I try spawn a new process in the background attempts fail when adding

-WindowSyle Hidden

The process stops as soon as the shell finishes.

When I add

-NoNewWindow

The process continues even when the PowerShell is closed.

Rather counterintuitive, not opening a new window would mean that the process closes when the caller closes and with a hiddon window I expect it to continue. The Get-Help is rather obscure about the behaviour when the calling process closes.

Could someone explain the difference between -WindowStyle hidden and -NoNewWindow? In both cases no new window is opened.

Powershell Object with an array element

$
0
0

Hi,
I'm working on a script to parse an ugly barely structured text file. I've got everything going apart from one specific area of functionality which troubles me.

There comes a point where it makes a great deal of sense to bunch a number of key/value pairs which I am grokking out of the text file up under a common custom object field name. Ultimately I want to convert the whole custom object, which I am building from a class template, to Json. In Json the field 'type' that I am looking to map is an array. It would take this kind of form:

{   "mundane_field": "mundane_piece_of_data",    "boring_number": 42,    "troublesome_field": [        {            "resource_name": "bugs bunny",            "resource_cost": 72725        },        {            "resource_name": "donald_duck",            "resource_cost": 5323        }    ],    "back_to_mundane": "doesn;t matter",    "final": "end is nigh"
}

In this example the troublesome field would need to contain an array of resource_names an resource_costs. 

My question is how should my class template be modelled to support this? I have tried a number of options like:

$myClassTemplate = {
[string]$mundane_field
[int]$boring_number
[array]$troublesome_field
# Now how do I reference / model the array elements? #
}

I hope this makes sense. In my application I may very well need to inject multiple class fields which contain arrays of key/value pairs and convert them to json and back again. Would very much appreciate a pointer.


Thanks!



Schedule Start process in background

$
0
0

When I try spawn a new process in the background attempts fail when adding

-WindowSyle Hidden

The process stops as soon as the shell finishes.

When I add

-NoNewWindow

The process continues even when the PowerShell is closed. But in this case the Powershell window stays open

Rather counterintuitive, not opening a new window would mean that the process closes when the caller closes and with a hiddon window I expect it to continue. The Get-Help is rather obscure about the behaviour when the calling process closes.

Could someone explain the difference between -WindowStyle hidden and -NoNewWindow? In both cases no new window is opened.

consulted Sources:


https://www.pluralsight.com/blog/it-ops/external-processes-in-powershell

https://community.spiceworks.com/how_to/17736-run-powershell-scripts-from-task-scheduler

PowerShell How to read a shortcut's target path

$
0
0

Hello All:)

Im kinda new with powershell, but i sometimes even surprise the experts sometimes, so you might say im right in middle.

So here is my question....

I have a variable that tells me where your mydocuments is redirected to. So based on the output of the variable, i want to read the target of a shortcut which i know is always there for everyone.

For example: test.lnk

How do i read the target of the shortcut using powershell?

 

Passing parameters from 1 script to another

$
0
0

Hi Guys - need help with below scenario. 

server 1 - script1.ps1

script 1 take 4 parameters from end users (username, computer name, domain & action). This script passes these values to script 2 which is kept at server 2

server 2 - script2.ps1

script 2 - takes those 4 parameters from script 1 and then perform that requested "action" on end user machine. 

I have script 2 but not sure how to pass values from script 1 to script 2. Can someone point me to right direction. The server 1 and server 2 cannot be changed. it remains as is.

Thank you!! 

I want to search for Latin words.

$
0
0
findstr  /s /i habitação *.*

Do I have to set the font to UTF-8? How?

I use PowerShell version 2.0

I appreciate help!


Targetting Get-ACL to a specific domain controller

$
0
0

Hi,

I have a script that creates various OU, security groups, GPO’s and then ties them together by linking the GPO’s and doing some access right delegation on the OU’s and GPO’s.

My problem is (I think) with AD replication.

I create a new OU using this command:

$NewOUDN  = "OU=Security Groups,OU=Region,DC=domain,DC=com"

$FirstDNPart = $NewOUDN.Split(",")[0].substring(3)

$LastDNPart = $NewOUDN.Split(",",2)[1]

New-ADOrganizationalUnit -Name "$FirstDNPart" -Path "$LastDNPart" -ProtectedFromAccidentalDeletion $True -Server $TargetDC -Description "$NewOUDescription"

So far, so good. Then I want to configure some ACE’s. That starts with getting the current ACL list so I run:

$acl = Get-ACL -Path $NewOUDN

The $TargetDC variable will usually not be the same as the logon server my workstation is connected to, so 'usually' (<> always) I get this error message:

Get-ACL : Cannot find path 'OU=Security Groups, OU=Region,DC=domain,DC=com' because it does not exist.

Ideally I would use -Server $TargetDC with the Get-ACL cmdlet, but that switch is not supported.

How do I know which domain controller the Get-ACL cmdlet is using?

How can I make sure the Get-ACL cmdlet is using a specific domain controller?

Any help/suggestions is appreciated.

Thanks!

Ashley.

How to swap values TRUE and FALSE in an exported CSV file

$
0
0

I've got a script that exports all AD users.  It's only two columns in a csv file.  The first is username and the second is Enabled.

Get-ADUser -Filter * -Properties * | Select @{Name="User ID";Expression={$_.SamAccountName}},@{Name="Disabled";Expression={$_.Enabled}} |export-csv -Path "C:\Path\Output.csv"

Get-ADUser returns a true or false value for the property "Enabled".  However, the person who uses the csv needs the column header to say Disabled and then return true or false.  I can change the column header no problem (shown above), but now i need some way to swap 'true' and 'false' in the csv.  Make sense?

I tried adding a second line..

get-content "C:\Path\Output.csv" | ForEach-Object -Process {$_ -replace 'True','False'} |set-content "C:\Path\UpdatedOutput.csv"

..But all that did was create a new csv file with all the values in the Disabled column set to False, not swap them around like i need it to do.

Any help is greatly appreciated.

Backup notifications will not send

$
0
0

Hi all, 

I am working to get backup email alerts setup for a client. I was able to get the script sending, but i had to enter my credentials each time. 

So i went with another users' suggestion and used plain text credentials. 

Here is the script i am using:

$username = "PAAC@peninsulaallergyandasthma.onmicrosoft.com"

$password = ConvertTo-SecureString "password" -AsPlainText -Force

$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)

Import-Module MSOnline

Connect-MSolService -Credential $psCred

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell-liveid/ -Credential $psCred -Authentication Basic -AllowRedirection 

Import-PSSession $Session -AllowClobber -DisableNameChecking

$SmtpClient = new-object system.net.mail.smtpClient

$MailMessage = New-Object system.net.mail.mailmessage

$Smtpclient.Host = "smtp.office365.com:587 -credentials -user PAAC@peninsulaallergyandasthma.onmicrosoft.com -passwordpassword"

$mailmessage.from = ("PAAC@peninsulaallergyandasthma.onmicrosoft.com")

$mailmessage.To.add("nathan@northtechgroup.com")

$mailmessage.Subject = “Backup Successful-WACP-2020”

$mailmessage.Body = “Successful backup for Veeam Agent for Windows backup job:Daily”

$smtpclient.Send($mailmessage)

I feel like I'm so close! 

My output from this script is as follows:

"

Exception calling "Send" with "1" argument(s): "Failure sending mail."
At C:\Users\Nathan\Desktop\EmailBackupAlert.ps1:29 char:1
+ $smtpclient.Send($mailmessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

"

I feel i have scoured the forums and cannot seem to get a straight answer as there are multiple scripts that claim to work. 

No MFA enabled on this account. I have verified send/receive using owa.  I have tested port 25 as well with no luck.

Thank you all for looking. 

Unable to Import-Module from a Runspace Pipeline

$
0
0

This command runs fine when directly run from a powershell console.

import-module az.sql

The exact same command fails when programatically run from C#. 

Pipeline pipeline = runspace.CreatePipeline();
var command = new Command("Import-Module");
command.Parameters.Add("Name", "Az.Sql");            
pipeline.Commands.Add(command);            
pipeline.Commands.Add("Out-String");
pipeline.Invoke();

This is the error.

The specified module 'Az.Sql' was not loaded because no valid module file was found in any module directory.

Now obviously the module is present, which is why it runs fine from the shell. It's located here.

...\Documents\WindowsPowerShell\Modules\Az.Sql\2.3.0

Any ideas as to what might be causing this? (tried running the test app as x64 too, but same result).

Error message " New-ADUser : No superior reference has been configured for the directory service. The directory service is therefore unable to issue referrals to objects outside this forest At line:25 char:15"

$
0
0

Hello, I have been assigned to put users into active directory using powershell but it isn't working at the moment and I cant figure out what's wrong.

Error message: 

New-ADUser : No superior reference has been configured for the directory service. The directory service is therefore unable to issue referrals to objects outside this forest At line:25 char:15 +               New-ADUser ` +               ~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (CN=Russell Orr,OU=Security:String) [New-ADUser], ADException     + FullyQualifiedErrorId : ActiveDirectoryServer:8406,Microsoft.ActiveDirectory.Management.Commands.NewADUser

The powershell code: 

#Enter a path to your import CSV file
$ADUsers = Import-csv C:\bulk_users11.csv

foreach ($User in $ADUsers)
{

       $Username    = $User.username
       $Password    = $User.password
       $Firstname   = $User.firstname
       $Lastname    = $User.lastname
    $Department = $User.department
       $OU           = $User.ou

       #Check if the user account already exists in AD
       if (Get-ADUser -F {SamAccountName -eq $Username})
       {
               #If user does exist, output a warning message
               Write-Warning "A user account $Username has already exist in Active Directory."
       }
       else
       {
              #If a user does not exist then create a new user account
          
        #Account will be created in the OU listed in the $OU variable in the CSV file; don’t forget to change the domain name in the"-UserPrincipalName" variable
              New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username@Cern.local" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -ChangePasswordAtLogon $True `
            -DisplayName "$Lastname, $Firstname" `
            -Department $Department `
            -Path $OU `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force)

       }
}

Get-ADUser pipeline to the Set-ADUser

$
0
0

I am trying to get the list of accounts from CSV and update to AD. If exists I will update else create new user.

Get-ADUser -SearchBase $searchbase -Filter {GivenName -eq "$user.'LastName'"} | ForEach-Object {set-aduser $_ -Surname "sample"}

The above operation is not doing anything nor throwing any kind of errors. can someone please let me know where I am doing wrong. tia.



need help with scrip to delete old computers from a domain

$
0
0

hey i mange to do the script to find all computers from 6 months ago

$dateOld = (Get-Date).AddDays(-180)
Get-ADComputer -Filter {LastLogonDate -lt $dateOld}  -Properties *|select Name, DNSHostName, Operatingsystem, LastLogonDate

no i want to add another filter  like

{OperatingSystem -Like '*Windows 7 Professional'}

but when i try to combine the the script docent work 

I want to find all windows 7 computers with oldest logon date more then 6 monthes


Powershell (and only Powershell) can't see network drives.

$
0
0

Having a bit of a strange issue with Powershell today, I went to open a script I had worked on last night and Powershell is telling me that it can't find my H: drive (my personal drive here at work) despite the fact that I'm browsing it just fine with my computer.

Screenshot with error below - note that the image I uploaded is on that same H: drive, so it seems to be just Powershell!



zarberg@gmail.com

Powershell windows opens and closes immidiately

$
0
0

Powershell does not work. The window opends and closes immidaitely. the Administrator version as well. This started after I rebooted Windows 10. Before it worked just fine

How do I get Powershell working again?

Incrementing PSCustomObject

$
0
0

Hi,

I've been prototyping quite a bit with pscustomobjects as containers for some fairly complex data structures I'm trying to model. By and large (and with a generous help from this forum), I'm getting there slowly. I have hit a bit of a blocker through.

Take this code:

$response           = [PSCustomObject]@{
    name            = "Pattern Name"
    hasAttributes   =  $False
    verified        = "06/02/2020 10:42:10.010"
    numEntities     = 3    
    entities        = [System.Collections.ArrayList]@()
}

$entity_1 = [PSCustomObject]@{
    name = "Publishing"
    type = "view"
    dataPoints = [System.Collections.ArrayList]@()
}


$dataPoint_1 = [PSCustomObject]@{
    Name = "printed"
    type = "integer"
}

$dataPoint_2 = [PSCustomObject]@{
    Name = "sales"
    type = "integer"
}

$entity_1.dataPoints.Add($dataPoint_1) | out-null
$entity_1.dataPoints.Add($dataPoint_2) | out-null 

"Entity 1:"
$entity_1 | ConvertTo-Json

$response.entities.Add($entity_1) | out-null
"Response"
$response | ConvertTo-Json

It generates the following output:

Entity 1:
{"name": "Publishing","type": "view","dataPoints": [
    {"Name": "printed","type": "integer"
    },
    {"Name": "sales","type": "integer"
    }
  ]
}
Response
{"name": "Pattern Name","hasAttributes": false,"verified": "06/02/2020 10:42:10.010","numEntities": 3,"entities": [
    {"name": "Publishing","type": "view","dataPoints": " "
    }
  ]
}

Entity 1:
{"name": "Publishing","type": "view","dataPoints": [
    {"Name": "printed","type": "integer"
    },
    {"Name": "sales","type": "integer"
    }
  ]
}
Response
{"name": "Pattern Name","hasAttributes": false,"verified": "06/02/2020 10:42:10.010","numEntities": 3,"entities": [
    {"name": "Publishing","type": "view","dataPoints": " "
    }
  ]
}

The entity_1 custom object is perfect, with the array of dataPoints. That is exactly how it should be.

How so that when I add the $entity_1 object to the $response.entities ArrayList the 'name' and 'type' from $entity_1 seem to get pushed into the field correctly but the dataPoints do not?

I had expected to see both the dataPoints ( "printed" and "sales" ) and their 'type' data to have made it into the dataPoints field.

Would be very grateful for any pointers to where I'm going wrong. 

Thanks.


Passing parameters on PowerShell.exe command not working with -File option

$
0
0

I saved this script as num.ps1:

param([int] $Num)
Write-Output $Num

Problem:

PS D:\> .\num.ps1 2MB
2097152

PS D:\> powershell.exe .\num.ps1 2MB
2097152

PS D:\> powershell.exe -File .\num.ps1 2MB
powershell.exe : D:\num.ps1 : Cannot process argument transformation on parameter 'Num'. Cannot convert value "2MB" to type "System.Int32".
Error: "Input string was
At line:1 char:1
+ powershell.exe -File .\num.ps1 2MB
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : NotSpecified: (D:\num.ps1 : Ca...put string was :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Same problem exists when launching PowerShell from cmd.exe.  Why does it fail on the last attempt?  More importantly, how can I make it work?


-Tony

Passing parameters on PowerShell.exe command line not working with -File option

$
0
0

I saved this script as num.ps1:

param([int] $Num)
Write-Output $Num

Problem:

PS D:\> .\num.ps1 2MB
2097152

PS D:\> powershell.exe .\num.ps1 2MB
2097152

PS D:\> powershell.exe -File .\num.ps1 2MB
powershell.exe : D:\num.ps1 : Cannot process argument transformation on parameter 'Num'. Cannot convert value "2MB" to type "System.Int32".
Error: "Input string was
At line:1 char:1
+ powershell.exe -File .\num.ps1 2MB
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : NotSpecified: (D:\num.ps1 : Ca...put string was :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Same problem exists when launching PowerShell from cmd.exe.  Why does it fail on the last attempt?  More importantly, how can I make it work?


-Tony

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>