UNPKG

@fmotion/pwsh

Version:
55 lines (45 loc) 1.79 kB
function convertArrayToPowershellArray(inputArrayObj, autoWrapOutput = 0) { const varName = Object.keys(inputArrayObj)[0]; const jsArray = inputArrayObj[varName]; if(!Array.isArray(jsArray)){ console.error('Passed object is not an array.') return $null } const convertValue = (value) => { if (Array.isArray(value)) { return `@(${value.map(convertValue).join(', ')})`; } if (value === undefined || value === null) { return '$null'; } if (typeof value === 'boolean') { return `$${value}`; } if (typeof value === 'string') { return `'${value.replace(/'/g, "''")}'`; // Escape single quotes } return value.toString(); }; let psArray = jsArray.map(convertValue); if (autoWrapOutput > 0) { let wrappedArray = ''; let currentLine = `$${varName} = @( `; const indent = ' '.repeat(currentLine.length); psArray.forEach((item, index) => { const itemWithComma = item + (index < psArray.length - 1 ? ', ' : ' '); const itemLength = itemWithComma.length; if ((currentLine.length + itemLength) > autoWrapOutput) { wrappedArray += `${currentLine.trimEnd()}\n`; currentLine = indent + itemWithComma; } else { currentLine += itemWithComma; } }); wrappedArray += currentLine.trimEnd() + ' )'; // Ensure closing parenthesis psArray = wrappedArray; } else { psArray = ' ' + psArray.join(', ') + ' )'; } return psArray; } exports.convertArrayToPowershellArray = convertArrayToPowershellArray;