powershell from chef resource powershell_script - powershell

I am trying to use one var declared outside chef resource powershell_script.
cn_name = powershell.exe hostname
puts cn_name ## will print like WIN-I5NP98N6JUE.cpteam.local
Now , i am trying to get the thumbprint of the root CA cert installed in this host.
powershell_script 'import CA_cert' do
code <<-EOH
$Thumbprint = (Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object {$_.Subject -match "CN="#{cn_name}""}).Thumbprint;
EOH
end
This is printing like : + ... ct -match "CN="WIN-I5NP98N6JUEcpteam.local""}).Thumbprint;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'WIN-I5NP98N6JUEcpteam.local""' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
Kindly help me here how to escape those quotes./ before quotes doesnt work.
Thanks!

That should be {$_.Subject -match "CN=#{cn_name}"}), you don't need the extra quotes at all.

try this to escape your extra quotes:
$Thumbprint = (Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object {$_.Subject -match "CN=`"#{cn_name}`""}).Thumbprint;

Related

How do I write a script to reboot a list of servers, but will EXCLUDE servers I don't want rebooted?

Being new to PowerShell I've been following some of the guidance in these posts to write a script for what's mentioned in the subject.
Here's the script:
Get-Content -Path C:\temp\Domain.txt | Restart-Computer -force | Where-Object { $._Name -notmatch "^(SERVER01)"}
Here's the error:
Restart-Computer : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:1 char:40
+ ... et-Content -Path C:\temp\Domain.txt | Restart-Computer -force | Where ...
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:PSObject) [Restart-Computer], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RestartComputerCommand
For reference, the DOMAIN.txt has a list of servers that will periodically change so I want to skip certain servers should they end up on the list.
The error simply means you have an empty line on your text file, you can filter the lines using .Where(..) method and exclude empty or white space lines with the help of [string]::IsNullOrWhiteSpace(..) method. I have changed -notmach for the containment operator -notin.
Note, -notin looks for an exact match within the collection $hostsToExclude.
$hostToExclude = 'server1', 'server2'
(Get-Content -Path C:\temp\Domain.txt).Where({
-not [string]::IsNullOrWhiteSpace($_) -and $_ -notin $hostToExclude
}) | Restart-Computer -Force
It's worth noting that, on your snippet, you're restarting the hosts before filtering the collection. Get-Content should be followed by Where-Object.

in jenkins(windows), powershell ls pipeline get null

This is my jenkins script.
Without pipeline, can see ls result list.
but when include pipeline with foreach, assign null to '$_'. Why??
stage('Module Build'){
gitlabCommitStatus('Module Build'){
powershell "${pythonPath} -m compileall ${srcPath}"
powershell "ls ${srcPath}\\*.py -Recurse | foreach {rm $_}"
}
}
error log
d:\...\durable-51664e76\powershellScript.ps1:1 char:33
+ ls src\*.py -Recurse | foreach {rm "null"}
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (D:\Jenkins\work...istributor\nu
ll:String) [Remove-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.Remov
eItemCommand
Try changing syntax to foreach-object
powershell "ls ${srcPath}\\*.py -Recurse | %{rm $_}"
further reading:
Difference between ForEach and ForEach-Object in powershell

I am looking to append windows host file get current dynamic ip and map it to a host name

I am looking to append windows host file get current dynamic ip and map it to a host name irrespective of current ip address.
i am getting below error
===============================================
Add-Content : A positional parameter cannot be found that accepts argument 'hostname1'.
At C:\Users\Opps\Desktop\power\New Text Document.ps1:6 char:3
+ {ac -Encoding UTF8 -value "$($env:windir)\system32\Drivers\etc\hosts ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Add-Content], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.AddContentCommand
================================================================================
Script :
$ip=get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1}
$ip.ipaddress[0]
$hst = $env:COMPUTERNAME
Set-ExecutionPolicy -ExecutionPolicy Unrestricted If ((Get-Content "$($env:windir)\system32\Drivers\etc\hosts" ) -notcontains "127.0.0.2 hostname1")
{ac -Encoding UTF8 "$($env:windir)\system32\Drivers\etc\hosts" ($ip.ipaddress[0]) ($hst) }
Add-Content is expecting a string as a value hence to change the type we need to encapsulate the value in quotes. To access an objects property e.g. $ip.ipaddress[0] while in quotes, in order for the text to not be treated literally, we must wrap it in brackets with a preceding dollar sign "$(...)" officially known as a subexpression operator (see mklement0's explanaton) . To ensure we are not duplicating an entry we run a quick check for the entry with the if statement only proceeding to add-content if both conditions of the if statement are met
$ip = get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1}
$ip.ipaddress[0]
$hst = $env:COMPUTERNAME
$hostfile = Get-Content "$($env:windir)\system32\Drivers\etc\hosts"
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
if ($hostfile -notcontains "127.0.0.2 hostname1" -and
(-not($hostfile -like "$($ip.ipaddress[0]) $hst"))) {
Add-Content -Encoding UTF8 "$($env:windir)\system32\Drivers\etc\hosts" "$($ip.ipaddress[0]) $hst"
}

PowerShell -replace function

I am trying to find and replace a strings in a file and then saving it to the original file in PowerShell.
I've tried doing
(Get-Content "C:\Users\anon\Desktop\test.txt")
-replace 'apple', 'apple1'
-replace 'bear' , 'bear1' |
Out-File test1.txt
pause
However, I keep getting
-replace : The term '-replace' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At C:\Users\Xing Chen\Desktop\test.ps1:2 char:1
+ -replace 'apple', 'apple1'
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-replace:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I've been able to use "abcd".replace() fine and according to the documentation -replace should work too.
There is nothing in your code to represent the line continuations and the interpreter is not seeing the -replace operators as part of the same command. You have two options to resolve this: escaping the newlines or putting the commands on the same line.
#(Get-Content "C:\Users\anon\Desktop\test.txt") -replace 'apple','apple1' -replace 'bear','bear1' |
Out-File -FilePath test1.txt
Pause
OR
#(Get-Content "C:\Users\anon\Desktop\test.txt") `
-replace 'apple','apple1' `
-replace 'bear','bear1' |
Out-File -FilePath test1.txt
Pause

Powershell Archive script win2008r2 problems

I created a ps-script to move MS SCCM backup folder to another location and delete folders older than 2 days :
$Date = Get-Date -format d.M.yyyy
$BackupDir = "\\Source_Servername\Folder1\Folder2"
$ArchiveDir = "\\Destination_Servername\Folder1\Folder2"
set-alias 7za "$ArchiveDir\7za.exe"
Get-Item "$ArchiveDir\*" |? {$_.psiscontainer -and $_.lastwritetime -le (get-date).adddays(-2)} |% {remove-item $_ -Recurse -Confirm:$false}
7za a -r "$ArchiveDir\$Date\$BackupDir.7z" $BackupDir
I created this using Win 8 and when i try to apply it on win2008r2 servers it fails with the following error :
Bad numeric constant: 7.
At E:\xxxxx\xxxxx\xxxx\Afterbackup.ps1:9 char:2
+ 7 <<<< za a -r "$ArchiveDir\$Date\$BackupDir.7z" $BackupDir
+ CategoryInfo : ParserError: (7:String) [], ParseException
+ FullyQualifiedErrorId : BadNumericConstant
It works when i enter the full path to 7za.exe like this :
\Destination_Servername\Folder1\Folder2\7za a -r "$ArchiveDir\$Date\$BackupDir.7z" $BackupDir
I'm new to powershell so i would appriciate any help :)
PowerShell v1 & v2 do not like commands that start with numbers. The issue seems to have been addressed in v3 and that's probably why it works on your workstation. You can work around this by placing a backtick in front of the alias when you execute it:
`7za a -r "$ArchiveDir\$Date\$BackupDir.7z" $BackupDir
Alternately, you can change the alias to not start with a number.